Update wheel from 0.30.0 to 0.31.0
[cached-property.git] / README.rst
1 ===============================
2 cached-property
3 ===============================
4
5 .. image:: https://img.shields.io/pypi/v/cached-property.svg
6 :target: https://pypi.python.org/pypi/cached-property
7
8 .. image:: https://img.shields.io/travis/pydanny/cached-property/master.svg
9 :target: https://travis-ci.org/pydanny/cached-property
10
11
12 A decorator for caching properties in classes.
13
14 Why?
15 -----
16
17 * Makes caching of time or computational expensive properties quick and easy.
18 * Because I got tired of copy/pasting this code from non-web project to non-web project.
19 * I needed something really simple that worked in Python 2 and 3.
20
21 How to use it
22 --------------
23
24 Let's define a class with an expensive property. Every time you stay there the
25 price goes up by $50!
26
27 .. code-block:: python
28
29 class Monopoly(object):
30
31 def __init__(self):
32 self.boardwalk_price = 500
33
34 @property
35 def boardwalk(self):
36 # In reality, this might represent a database call or time
37 # intensive task like calling a third-party API.
38 self.boardwalk_price += 50
39 return self.boardwalk_price
40
41 Now run it:
42
43 .. code-block:: python
44
45 >>> monopoly = Monopoly()
46 >>> monopoly.boardwalk
47 550
48 >>> monopoly.boardwalk
49 600
50
51 Let's convert the boardwalk property into a ``cached_property``.
52
53 .. code-block:: python
54
55 from cached_property import cached_property
56
57 class Monopoly(object):
58
59 def __init__(self):
60 self.boardwalk_price = 500
61
62 @cached_property
63 def boardwalk(self):
64 # Again, this is a silly example. Don't worry about it, this is
65 # just an example for clarity.
66 self.boardwalk_price += 50
67 return self.boardwalk_price
68
69 Now when we run it the price stays at $550.
70
71 .. code-block:: python
72
73 >>> monopoly = Monopoly()
74 >>> monopoly.boardwalk
75 550
76 >>> monopoly.boardwalk
77 550
78 >>> monopoly.boardwalk
79 550
80
81 Why doesn't the value of ``monopoly.boardwalk`` change? Because it's a **cached property**!
82
83 Invalidating the Cache
84 ----------------------
85
86 Results of cached functions can be invalidated by outside forces. Let's demonstrate how to force the cache to invalidate:
87
88 .. code-block:: python
89
90 >>> monopoly = Monopoly()
91 >>> monopoly.boardwalk
92 550
93 >>> monopoly.boardwalk
94 550
95 >>> # invalidate the cache
96 >>> del monopoly.__dict__['boardwalk']
97 >>> # request the boardwalk property again
98 >>> monopoly.boardwalk
99 600
100 >>> monopoly.boardwalk
101 600
102
103 Working with Threads
104 ---------------------
105
106 What if a whole bunch of people want to stay at Boardwalk all at once? This means using threads, which
107 unfortunately causes problems with the standard ``cached_property``. In this case, switch to using the
108 ``threaded_cached_property``:
109
110 .. code-block:: python
111
112 from cached_property import threaded_cached_property
113
114 class Monopoly(object):
115
116 def __init__(self):
117 self.boardwalk_price = 500
118
119 @threaded_cached_property
120 def boardwalk(self):
121 """threaded_cached_property is really nice for when no one waits
122 for other people to finish their turn and rudely start rolling
123 dice and moving their pieces."""
124
125 sleep(1)
126 self.boardwalk_price += 50
127 return self.boardwalk_price
128
129 Now use it:
130
131 .. code-block:: python
132
133 >>> from threading import Thread
134 >>> from monopoly import Monopoly
135 >>> monopoly = Monopoly()
136 >>> threads = []
137 >>> for x in range(10):
138 >>> thread = Thread(target=lambda: monopoly.boardwalk)
139 >>> thread.start()
140 >>> threads.append(thread)
141
142 >>> for thread in threads:
143 >>> thread.join()
144
145 >>> self.assertEqual(m.boardwalk, 550)
146
147
148 Working with async/await (Python 3.5+)
149 --------------------------------------
150
151 The cached property can be async, in which case you have to use await
152 as usual to get the value. Because of the caching, the value is only
153 computed once and then cached:
154
155 .. code-block:: python
156
157 from cached_property import cached_property
158
159 class Monopoly(object):
160
161 def __init__(self):
162 self.boardwalk_price = 500
163
164 @cached_property
165 async def boardwalk(self):
166 self.boardwalk_price += 50
167 return self.boardwalk_price
168
169 Now use it:
170
171 .. code-block:: python
172
173 >>> async def print_boardwalk():
174 ... monopoly = Monopoly()
175 ... print(await monopoly.boardwalk)
176 ... print(await monopoly.boardwalk)
177 ... print(await monopoly.boardwalk)
178 >>> import asyncio
179 >>> asyncio.get_event_loop().run_until_complete(print_boardwalk())
180 550
181 550
182 550
183
184 Note that this does not work with threading either, most asyncio
185 objects are not thread-safe. And if you run separate event loops in
186 each thread, the cached version will most likely have the wrong event
187 loop. To summarize, either use cooperative multitasking (event loop)
188 or threading, but not both at the same time.
189
190
191 Timing out the cache
192 --------------------
193
194 Sometimes you want the price of things to reset after a time. Use the ``ttl``
195 versions of ``cached_property`` and ``threaded_cached_property``.
196
197 .. code-block:: python
198
199 import random
200 from cached_property import cached_property_with_ttl
201
202 class Monopoly(object):
203
204 @cached_property_with_ttl(ttl=5) # cache invalidates after 5 seconds
205 def dice(self):
206 # I dare the reader to implement a game using this method of 'rolling dice'.
207 return random.randint(2,12)
208
209 Now use it:
210
211 .. code-block:: python
212
213 >>> monopoly = Monopoly()
214 >>> monopoly.dice
215 10
216 >>> monopoly.dice
217 10
218 >>> from time import sleep
219 >>> sleep(6) # Sleeps long enough to expire the cache
220 >>> monopoly.dice
221 3
222 >>> monopoly.dice
223 3
224
225 **Note:** The ``ttl`` tools do not reliably allow the clearing of the cache. This
226 is why they are broken out into seperate tools. See https://github.com/pydanny/cached-property/issues/16.
227
228 Credits
229 --------
230
231 * Pip, Django, Werkzueg, Bottle, Pyramid, and Zope for having their own implementations. This package originally used an implementation that matched the Bottle version.
232 * Reinout Van Rees for pointing out the `cached_property` decorator to me.
233 * My awesome wife `@audreyr`_ who created `cookiecutter`_, which meant rolling this out took me just 15 minutes.
234 * @tinche for pointing out the threading issue and providing a solution.
235 * @bcho for providing the time-to-expire feature
236
237 .. _`@audreyr`: https://github.com/audreyr
238 .. _`cookiecutter`: https://github.com/audreyr/cookiecutter
239
240 Support This Project
241 ---------------------------
242
243 This project is maintained by volunteers. Support their efforts by spreading the word about:
244
245 .. image:: https://cdn.shopify.com/s/files/1/0304/6901/t/2/assets/logo.png?8399580890922549623
246 :name: Two Scoops Press
247 :align: center
248 :alt: Two Scoops Press
249 :target: https://www.twoscoopspress.com