1 ===============================
3 ===============================
5 .. image:: https://img.shields.io/pypi/v/cached-property.svg
6 :target: https://pypi.python.org/pypi/cached-property
8 .. image:: https://img.shields.io/travis/pydanny/cached-property/master.svg
9 :target: https://travis-ci.org/pydanny/cached-property
12 A decorator for caching properties in classes.
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.
24 Let's define a class with an expensive property. Every time you stay there the
27 .. code-block:: python
29 class Monopoly(object):
32 self.boardwalk_price = 500
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
43 .. code-block:: python
45 >>> monopoly = Monopoly()
46 >>> monopoly.boardwalk
48 >>> monopoly.boardwalk
51 Let's convert the boardwalk property into a ``cached_property``.
53 .. code-block:: python
55 from cached_property import cached_property
57 class Monopoly(object):
60 self.boardwalk_price = 500
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
69 Now when we run it the price stays at $550.
71 .. code-block:: python
73 >>> monopoly = Monopoly()
74 >>> monopoly.boardwalk
76 >>> monopoly.boardwalk
78 >>> monopoly.boardwalk
81 Why doesn't the value of ``monopoly.boardwalk`` change? Because it's a **cached property**!
83 Invalidating the Cache
84 ----------------------
86 Results of cached functions can be invalidated by outside forces. Let's demonstrate how to force the cache to invalidate:
88 .. code-block:: python
90 >>> monopoly = Monopoly()
91 >>> monopoly.boardwalk
93 >>> monopoly.boardwalk
95 >>> # invalidate the cache
96 >>> del monopoly.__dict__['boardwalk']
97 >>> # request the boardwalk property again
98 >>> monopoly.boardwalk
100 >>> monopoly.boardwalk
104 ---------------------
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``:
110 .. code-block:: python
112 from cached_property import threaded_cached_property
114 class Monopoly(object):
117 self.boardwalk_price = 500
119 @threaded_cached_property
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."""
126 self.boardwalk_price += 50
127 return self.boardwalk_price
131 .. code-block:: python
133 >>> from threading import Thread
134 >>> from monopoly import Monopoly
135 >>> monopoly = Monopoly()
137 >>> for x in range(10):
138 >>> thread = Thread(target=lambda: monopoly.boardwalk)
140 >>> threads.append(thread)
142 >>> for thread in threads:
145 >>> self.assertEqual(m.boardwalk, 550)
148 Working with async/await (Python 3.5+)
149 --------------------------------------
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:
155 .. code-block:: python
157 from cached_property import cached_property
159 class Monopoly(object):
162 self.boardwalk_price = 500
165 async def boardwalk(self):
166 self.boardwalk_price += 50
167 return self.boardwalk_price
171 .. code-block:: python
173 >>> async def print_boardwalk():
174 ... monopoly = Monopoly()
175 ... print(await monopoly.boardwalk)
176 ... print(await monopoly.boardwalk)
177 ... print(await monopoly.boardwalk)
179 >>> asyncio.get_event_loop().run_until_complete(print_boardwalk())
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.
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``.
197 .. code-block:: python
200 from cached_property import cached_property_with_ttl
202 class Monopoly(object):
204 @cached_property_with_ttl(ttl=5) # cache invalidates after 5 seconds
206 # I dare the reader to implement a game using this method of 'rolling dice'.
207 return random.randint(2,12)
211 .. code-block:: python
213 >>> monopoly = Monopoly()
218 >>> from time import sleep
219 >>> sleep(6) # Sleeps long enough to expire the cache
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.
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
237 .. _`@audreyr`: https://github.com/audreyr
238 .. _`cookiecutter`: https://github.com/audreyr/cookiecutter
241 ---------------------------
243 This project is maintained by volunteers. Support their efforts by spreading the word about:
245 .. image:: https://cdn.shopify.com/s/files/1/0304/6901/t/2/assets/logo.png?8399580890922549623
246 :name: Two Scoops Press
248 :alt: Two Scoops Press
249 :target: https://www.twoscoopspress.com