Debian Codegraph @

PKG-INFO

raw
1 Metadata-Version: 2.1
2 Name: cached-property
3 Version: 2.0.1
4 Summary: A decorator for caching properties in classes.
5 Home-page: https://github.com/pydanny/cached-property
6 Author: Daniel Roy Greenfeld
7 Author-email: [email protected]
8 License: BSD
9 Keywords: cached-property
10 Classifier: Development Status :: 5 - Production/Stable
11 Classifier: Intended Audience :: Developers
12 Classifier: License :: OSI Approved :: BSD License
13 Classifier: Natural Language :: English
14 Classifier: Programming Language :: Python :: 3
15 Classifier: Programming Language :: Python :: 3.8
16 Classifier: Programming Language :: Python :: 3.9
17 Classifier: Programming Language :: Python :: 3.10
18 Classifier: Programming Language :: Python :: 3.11
19 Classifier: Programming Language :: Python :: 3.12
20 Classifier: Programming Language :: Python :: 3.13
21 Classifier: Programming Language :: Python :: Implementation :: CPython
22 Classifier: Programming Language :: Python :: Implementation :: PyPy
23 Requires-Python: >=3.8
24 Description-Content-Type: text/markdown
25 License-File: LICENSE
26 License-File: AUTHORS.md
27
28 # cached-property
29
30 [![Github Actions status](https://github.com/pydanny/cached-property/workflows/Python%20package/badge.svg)](https://github.com/pydanny/cached-property/actions)
31 [![PyPI](https://img.shields.io/pypi/v/cached-property.svg)](https://pypi.python.org/pypi/cached-property)
32 [![Code style: ruff](https://img.shields.io/badge/code%20style-ruff-000000.svg)](https://github.com/astral-sh/ruff)
33
34 A decorator for caching properties in classes.
35
36 ## Why?
37
38 * Makes caching of time or computational expensive properties quick and easy.
39 * Because I got tired of copy/pasting this code from non-web project to non-web project.
40 * I needed something really simple that worked in Python 2 and 3.
41 (Python 3.8 added a version of this decorator as [`@functools.cached_property`](https://docs.python.org/3.12/library/functools.html#functools.cached_property).)
42
43 ## How to use it
44
45 Let's define a class with an expensive property. Every time you stay there the
46 price goes up by $50!
47
48 ```python
49 class Monopoly:
50
51 def __init__(self):
52 self.boardwalk_price = 500
53
54 @property
55 def boardwalk(self):
56 # In reality, this might represent a database call or time
57 # intensive task like calling a third-party API.
58 self.boardwalk_price += 50
59 return self.boardwalk_price
60 ```
61
62 Now run it:
63
64 ```python
65 >>> monopoly = Monopoly()
66 >>> monopoly.boardwalk
67 550
68 >>> monopoly.boardwalk
69 600
70 ```
71
72 Let's convert the boardwalk property into a `cached_property`.
73
74 ```python
75 from cached_property import cached_property
76
77 class Monopoly(object):
78
79 def __init__(self):
80 self.boardwalk_price = 500
81
82 @cached_property
83 def boardwalk(self):
84 # Again, this is a silly example. Don't worry about it, this is
85 # just an example for clarity.
86 self.boardwalk_price += 50
87 return self.boardwalk_price
88 ```
89
90 Now when we run it the price stays at $550.
91
92 ```python
93 >>> monopoly = Monopoly()
94 >>> monopoly.boardwalk
95 550
96 >>> monopoly.boardwalk
97 550
98 >>> monopoly.boardwalk
99 550
100 ```
101
102 Why doesn't the value of `monopoly.boardwalk` change? Because it's a **cached property**!
103
104 ## Invalidating the Cache
105
106 Results of cached functions can be invalidated by outside forces. Let's demonstrate how to force the cache to invalidate:
107
108 ```python
109 >>> monopoly = Monopoly()
110 >>> monopoly.boardwalk
111 550
112 >>> monopoly.boardwalk
113 550
114 >>> # invalidate the cache
115 >>> del monopoly.__dict__['boardwalk']
116 >>> # request the boardwalk property again
117 >>> monopoly.boardwalk
118 600
119 >>> monopoly.boardwalk
120 600
121 ```
122
123 ## Working with Threads
124
125 What if a whole bunch of people want to stay at Boardwalk all at once? This means using threads, which
126 unfortunately causes problems with the standard `cached_property`. In this case, switch to using the
127 `threaded_cached_property`:
128
129 ```python
130 from cached_property import threaded_cached_property
131
132 class Monopoly:
133
134 def __init__(self):
135 self.boardwalk_price = 500
136
137 @threaded_cached_property
138 def boardwalk(self):
139 """threaded_cached_property is really nice for when no one waits
140 for other people to finish their turn and rudely start rolling
141 dice and moving their pieces."""
142
143 sleep(1)
144 self.boardwalk_price += 50
145 return self.boardwalk_price
146 ```
147
148 Now use it:
149
150 ```python
151 >>> from threading import Thread
152 >>> from monopoly import Monopoly
153 >>> monopoly = Monopoly()
154 >>> threads = []
155 >>> for x in range(10):
156 >>> thread = Thread(target=lambda: monopoly.boardwalk)
157 >>> thread.start()
158 >>> threads.append(thread)
159
160 >>> for thread in threads:
161 >>> thread.join()
162
163 >>> self.assertEqual(m.boardwalk, 550)
164 ```
165
166 ## Working with async/await
167
168 The cached property can be async, in which case you have to use await
169 as usual to get the value. Because of the caching, the value is only
170 computed once and then cached:
171
172 ```python
173 from cached_property import cached_property
174
175 class Monopoly:
176
177 def __init__(self):
178 self.boardwalk_price = 500
179
180 @cached_property
181 async def boardwalk(self):
182 self.boardwalk_price += 50
183 return self.boardwalk_price
184 ```
185
186 Now use it:
187
188 ```python
189 >>> async def print_boardwalk():
190 ... monopoly = Monopoly()
191 ... print(await monopoly.boardwalk)
192 ... print(await monopoly.boardwalk)
193 ... print(await monopoly.boardwalk)
194 >>> import asyncio
195 >>> asyncio.get_event_loop().run_until_complete(print_boardwalk())
196 550
197 550
198 550
199 ```
200
201 Note that this does not work with threading either, most asyncio
202 objects are not thread-safe. And if you run separate event loops in
203 each thread, the cached version will most likely have the wrong event
204 loop. To summarize, either use cooperative multitasking (event loop)
205 or threading, but not both at the same time.
206
207 ## Timing out the cache
208
209 Sometimes you want the price of things to reset after a time. Use the `ttl`
210 versions of `cached_property` and `threaded_cached_property`.
211
212 ```python
213 import random
214 from cached_property import cached_property_with_ttl
215
216 class Monopoly(object):
217
218 @cached_property_with_ttl(ttl=5) # cache invalidates after 5 seconds
219 def dice(self):
220 # I dare the reader to implement a game using this method of 'rolling dice'.
221 return random.randint(2,12)
222 ```
223
224 Now use it:
225
226 ```python
227 >>> monopoly = Monopoly()
228 >>> monopoly.dice
229 10
230 >>> monopoly.dice
231 10
232 >>> from time import sleep
233 >>> sleep(6) # Sleeps long enough to expire the cache
234 >>> monopoly.dice
235 3
236 >>> monopoly.dice
237 3
238 ```
239
240 **Note:** The `ttl` tools do not reliably allow the clearing of the cache. This
241 is why they are broken out into seperate tools. See https://github.com/pydanny/cached-property/issues/16.
242
243 ## Credits
244
245 * Pip, Django, Werkzeug, Bottle, Pyramid, and Zope for having their own implementations. This package originally used an implementation that matched the Bottle version.
246 * Reinout Van Rees for pointing out the `cached_property` decorator to me.
247 * My awesome wife [@audreyfeldroy](https://github.com/audreyfeldroy) who created [`cookiecutter`](https://github.com/cookiecutter/cookiecutter), which meant rolling this out took me just 15 minutes.
248 * @tinche for pointing out the threading issue and providing a solution.
249 * @bcho for providing the time-to-expire feature
250
251
252
253 # History
254
255 ## 2.0.1 (2024-10-25)
256
257 * Via `python_requires` specifies that cached_property is for Python version 3.8 or higher
258 * Officiall drop support for Python 2.6
259
260 ## 2.0.0 (2024-10-25)
261
262 * Remove support for Python versions < 3.8
263 * Add formal support for Python versions up to 3.13
264 * Switch to Markdown for docs
265 * Migrate from black to ruff
266
267 ## 1.5.2 (2020-09-21)
268
269 * Add formal support for Python 3.8
270 * Remove formal support for Python 3.4
271 * Switch from Travis to GitHub actions
272 * Made tests pass flake8 for Python 2.7
273
274 ## 1.5.1 (2018-08-05)
275
276 * Added formal support for Python 3.7
277 * Removed formal support for Python 3.3
278
279 ## 1.4.3 (2018-06-14)
280
281 * Catch SyntaxError from asyncio import on older versions of Python, thanks to @asottile
282
283 ## 1.4.2 (2018-04-08)
284
285 * Really fixed tests, thanks to @pydanny
286
287 ## 1.4.1 (2018-04-08)
288
289 * Added conftest.py to manifest so tests work properly off the tarball, thanks to @dotlambda
290 * Ensured new asyncio tests didn't break Python 2.7 builds on Debian, thanks to @pydanny
291 * Code formatting via black, thanks to @pydanny and @ambv
292
293 ## 1.4.0 (2018-02-25)
294
295 * Added asyncio support, thanks to @vbraun
296 * Remove Python 2.6 support, whose end of life was 5 years ago, thanks to @pydanny
297
298 ## 1.3.1 (2017-09-21)
299
300 * Validate for Python 3.6
301
302 ## 1.3.0 (2015-11-24)
303
304 * Drop some non-ASCII characters from HISTORY.rst, thanks to @AdamWill
305 * Added official support for Python 3.5, thanks to @pydanny and @audreyr
306 * Removed confusingly placed lock from example, thanks to @ionelmc
307 * Corrected invalidation cache documentation, thanks to @proofit404
308 * Updated to latest Travis-CI environment, thanks to @audreyr
309
310 ## 1.2.0 (2015-04-28)
311
312 * Overall code and test refactoring, thanks to @gsakkis
313 * Allow the del statement for resetting cached properties with ttl instead of del obj._cache[attr], thanks to @gsakkis.
314 * Uncovered a bug in PyPy, https://bitbucket.org/pypy/pypy/issue/2033/attributeerror-object-attribute-is-read, thanks to @gsakkis
315 * Fixed threaded_cached_property_with_ttl to actually be thread-safe, thanks to @gsakkis
316
317 ## 1.1.0 (2015-04-04)
318
319 * Regression: As the cache was not always clearing, we've broken out the time to expire feature to its own set of specific tools, thanks to @pydanny
320 * Fixed typo in README, thanks to @zoidbergwill
321
322 ## 1.0.0 (2015-02-13)
323
324 * Added timed to expire feature to `cached_property` decorator.
325 * **Backwards incompatiblity**: Changed `del monopoly.boardwalk` to `del monopoly['boardwalk']` in order to support the new TTL feature.
326
327 ## 0.1.5 (2014-05-20)
328
329 * Added threading support with new `threaded_cached_property` decorator
330 * Documented cache invalidation
331 * Updated credits
332 * Sourced the bottle implementation
333
334 ## 0.1.4 (2014-05-17)
335
336 * Fix the dang-blarged py_modules argument.
337
338 ## 0.1.3 (2014-05-17)
339
340 * Removed import of package into `setup.py`
341
342 ## 0.1.2 (2014-05-17)
343
344 * Documentation fixes. Not opening up a RTFD instance for this because it's so simple to use.
345
346 ## 0.1.1 (2014-05-17)
347
348 * setup.py fix. Whoops!
349
350 ## 0.1.0 (2014-05-17)
351
352 * First release on PyPI.