././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1729871022.3852048 cached_property-2.0.1/0000755000076500000240000000000014706736256013404 5ustar00drgstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729852089.0 cached_property-2.0.1/AUTHORS.md0000644000076500000240000000063414706671271015051 0ustar00drgstaff# Credits ## Development Lead * Daniel Roy Greenfeld (@pydanny) * Audrey Roy Greenfeld (@audreyfeldroy) ## Contributors * Tin Tvrtković * @bcho * George Sakkis (@gsakkis) * Adam Williamson * Ionel Cristian Mărieș (@ionelmc) * Malyshev Artem (@proofit404) * Volker Braun (@vbraun) * Qudus Oladipo (@stikks) * Bartosz Sokorski (@secrus) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729852089.0 cached_property-2.0.1/CONTRIBUTING.md0000644000076500000240000000642414706671271015636 0ustar00drgstaff# Contributing Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given. You can contribute in many ways: ## Types of Contributions ### Report Bugs Report bugs at https://github.com/pydanny/cached-property/issues. If you are reporting a bug, please include: * Your operating system name and version. * Any details about your local setup that might be helpful in troubleshooting. * Detailed steps to reproduce the bug. ### Fix Bugs Look through the GitHub issues for bugs. Anything tagged with "bug" is open to whoever wants to implement it. ### Implement features Look through the GitHub issues for features. Anything tagged with "feature" is open to whoever wants to implement it. ### Write Documentation cached-property could always use more documentation, whether as part of the official cached-property docs, in docstrings, or even on the web in blog posts, articles, and such. ### Submit Feedback The best way to send feedback is to file an issue at https://github.com/pydanny/cached-property/issues. If you are proposing a feature: * Explain in detail how it would work. * Keep the scope as narrow as possible, to make it easier to implement. * Remember that this is a volunteer-driven project, and that contributions are welcome :) ## Get started! Ready to contribute? Here's how to set up `cached-property` for local development. 1. Fork the `cached-property` repo on GitHub. 2. Clone your fork locally:: ```bash $ git clone git@github.com:your_name_here/cached-property.git ``` 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development: ```bash $ mkvirtualenv cached-property $ cd cached-property/ $ python setup.py develop ``` 4. Create a branch for local development: ```bash $ git checkout -b name-of-your-bugfix-or-feature ``` Now you can make your changes locally. 5. Clean up the formatting (must be running at least Python 3.8): ```bash $ pip install -U ruff $ ruff format . ``` 6. When you're done making changes, check that your changes pass the tests, including testing other Python versions with tox: ```bash $ pytest tests/ $ tox ``` To get tox, just pip install it into your virtualenv. 7. Commit your changes and push your branch to GitHub:: ```bash $ git add . $ git commit -m "Your detailed description of your changes." $ git push origin name-of-your-bugfix-or-feature ``` 8. Submit a pull request through the GitHub website. ## Pull Request Guidelines Before you submit a pull request, check that it meets these guidelines: 1. The pull request should include tests. 2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.md. 3. The pull request should work for all Python versions defined as classifiers in `setup.py`. Make sure that the [GitHub Action tests](https://github.com/pydanny/cached-property/actions) pass for all supported Python versions. ## Tips To run a subset of tests: ```bash $ pytest tests/test_cached-property.py $ pytest tests/test_cached-property.py::TestCachedProperty ``` ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729871009.0 cached_property-2.0.1/HISTORY.md0000644000076500000240000000572514706736241015072 0ustar00drgstaff# History ## 2.0.1 (2024-10-25) * Via `python_requires` specifies that cached_property is for Python version 3.8 or higher * Officiall drop support for Python 2.6 ## 2.0.0 (2024-10-25) * Remove support for Python versions < 3.8 * Add formal support for Python versions up to 3.13 * Switch to Markdown for docs * Migrate from black to ruff ## 1.5.2 (2020-09-21) * Add formal support for Python 3.8 * Remove formal support for Python 3.4 * Switch from Travis to GitHub actions * Made tests pass flake8 for Python 2.7 ## 1.5.1 (2018-08-05) * Added formal support for Python 3.7 * Removed formal support for Python 3.3 ## 1.4.3 (2018-06-14) * Catch SyntaxError from asyncio import on older versions of Python, thanks to @asottile ## 1.4.2 (2018-04-08) * Really fixed tests, thanks to @pydanny ## 1.4.1 (2018-04-08) * Added conftest.py to manifest so tests work properly off the tarball, thanks to @dotlambda * Ensured new asyncio tests didn't break Python 2.7 builds on Debian, thanks to @pydanny * Code formatting via black, thanks to @pydanny and @ambv ## 1.4.0 (2018-02-25) * Added asyncio support, thanks to @vbraun * Remove Python 2.6 support, whose end of life was 5 years ago, thanks to @pydanny ## 1.3.1 (2017-09-21) * Validate for Python 3.6 ## 1.3.0 (2015-11-24) * Drop some non-ASCII characters from HISTORY.rst, thanks to @AdamWill * Added official support for Python 3.5, thanks to @pydanny and @audreyr * Removed confusingly placed lock from example, thanks to @ionelmc * Corrected invalidation cache documentation, thanks to @proofit404 * Updated to latest Travis-CI environment, thanks to @audreyr ## 1.2.0 (2015-04-28) * Overall code and test refactoring, thanks to @gsakkis * Allow the del statement for resetting cached properties with ttl instead of del obj._cache[attr], thanks to @gsakkis. * Uncovered a bug in PyPy, https://bitbucket.org/pypy/pypy/issue/2033/attributeerror-object-attribute-is-read, thanks to @gsakkis * Fixed threaded_cached_property_with_ttl to actually be thread-safe, thanks to @gsakkis ## 1.1.0 (2015-04-04) * 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 * Fixed typo in README, thanks to @zoidbergwill ## 1.0.0 (2015-02-13) * Added timed to expire feature to `cached_property` decorator. * **Backwards incompatiblity**: Changed `del monopoly.boardwalk` to `del monopoly['boardwalk']` in order to support the new TTL feature. ## 0.1.5 (2014-05-20) * Added threading support with new `threaded_cached_property` decorator * Documented cache invalidation * Updated credits * Sourced the bottle implementation ## 0.1.4 (2014-05-17) * Fix the dang-blarged py_modules argument. ## 0.1.3 (2014-05-17) * Removed import of package into `setup.py` ## 0.1.2 (2014-05-17) * Documentation fixes. Not opening up a RTFD instance for this because it's so simple to use. ## 0.1.1 (2014-05-17) * setup.py fix. Whoops! ## 0.1.0 (2014-05-17) * First release on PyPI. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729852089.0 cached_property-2.0.1/LICENSE0000644000076500000240000000270714706671271014412 0ustar00drgstaffCopyright (c) 2015, Daniel Greenfeld All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of cached-property nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729852089.0 cached_property-2.0.1/MANIFEST.in0000644000076500000240000000023314706671271015133 0ustar00drgstaffinclude AUTHORS.md include CONTRIBUTING.md include HISTORY.md include LICENSE include README.md recursive-include tests * recursive-exclude * __pycache__ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1729871022.3851142 cached_property-2.0.1/PKG-INFO0000644000076500000240000002404114706736256014502 0ustar00drgstaffMetadata-Version: 2.1 Name: cached-property Version: 2.0.1 Summary: A decorator for caching properties in classes. Home-page: https://github.com/pydanny/cached-property Author: Daniel Roy Greenfeld Author-email: daniel@feldroy.com License: BSD Keywords: cached-property Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Natural Language :: English Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Requires-Python: >=3.8 Description-Content-Type: text/markdown License-File: LICENSE License-File: AUTHORS.md # cached-property [![Github Actions status](https://github.com/pydanny/cached-property/workflows/Python%20package/badge.svg)](https://github.com/pydanny/cached-property/actions) [![PyPI](https://img.shields.io/pypi/v/cached-property.svg)](https://pypi.python.org/pypi/cached-property) [![Code style: ruff](https://img.shields.io/badge/code%20style-ruff-000000.svg)](https://github.com/astral-sh/ruff) A decorator for caching properties in classes. ## Why? * Makes caching of time or computational expensive properties quick and easy. * Because I got tired of copy/pasting this code from non-web project to non-web project. * I needed something really simple that worked in Python 2 and 3. (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).) ## How to use it Let's define a class with an expensive property. Every time you stay there the price goes up by $50! ```python class Monopoly: def __init__(self): self.boardwalk_price = 500 @property def boardwalk(self): # In reality, this might represent a database call or time # intensive task like calling a third-party API. self.boardwalk_price += 50 return self.boardwalk_price ``` Now run it: ```python >>> monopoly = Monopoly() >>> monopoly.boardwalk 550 >>> monopoly.boardwalk 600 ``` Let's convert the boardwalk property into a `cached_property`. ```python from cached_property import cached_property class Monopoly(object): def __init__(self): self.boardwalk_price = 500 @cached_property def boardwalk(self): # Again, this is a silly example. Don't worry about it, this is # just an example for clarity. self.boardwalk_price += 50 return self.boardwalk_price ``` Now when we run it the price stays at $550. ```python >>> monopoly = Monopoly() >>> monopoly.boardwalk 550 >>> monopoly.boardwalk 550 >>> monopoly.boardwalk 550 ``` Why doesn't the value of `monopoly.boardwalk` change? Because it's a **cached property**! ## Invalidating the Cache Results of cached functions can be invalidated by outside forces. Let's demonstrate how to force the cache to invalidate: ```python >>> monopoly = Monopoly() >>> monopoly.boardwalk 550 >>> monopoly.boardwalk 550 >>> # invalidate the cache >>> del monopoly.__dict__['boardwalk'] >>> # request the boardwalk property again >>> monopoly.boardwalk 600 >>> monopoly.boardwalk 600 ``` ## Working with Threads What if a whole bunch of people want to stay at Boardwalk all at once? This means using threads, which unfortunately causes problems with the standard `cached_property`. In this case, switch to using the `threaded_cached_property`: ```python from cached_property import threaded_cached_property class Monopoly: def __init__(self): self.boardwalk_price = 500 @threaded_cached_property def boardwalk(self): """threaded_cached_property is really nice for when no one waits for other people to finish their turn and rudely start rolling dice and moving their pieces.""" sleep(1) self.boardwalk_price += 50 return self.boardwalk_price ``` Now use it: ```python >>> from threading import Thread >>> from monopoly import Monopoly >>> monopoly = Monopoly() >>> threads = [] >>> for x in range(10): >>> thread = Thread(target=lambda: monopoly.boardwalk) >>> thread.start() >>> threads.append(thread) >>> for thread in threads: >>> thread.join() >>> self.assertEqual(m.boardwalk, 550) ``` ## Working with async/await The cached property can be async, in which case you have to use await as usual to get the value. Because of the caching, the value is only computed once and then cached: ```python from cached_property import cached_property class Monopoly: def __init__(self): self.boardwalk_price = 500 @cached_property async def boardwalk(self): self.boardwalk_price += 50 return self.boardwalk_price ``` Now use it: ```python >>> async def print_boardwalk(): ... monopoly = Monopoly() ... print(await monopoly.boardwalk) ... print(await monopoly.boardwalk) ... print(await monopoly.boardwalk) >>> import asyncio >>> asyncio.get_event_loop().run_until_complete(print_boardwalk()) 550 550 550 ``` Note that this does not work with threading either, most asyncio objects are not thread-safe. And if you run separate event loops in each thread, the cached version will most likely have the wrong event loop. To summarize, either use cooperative multitasking (event loop) or threading, but not both at the same time. ## Timing out the cache Sometimes you want the price of things to reset after a time. Use the `ttl` versions of `cached_property` and `threaded_cached_property`. ```python import random from cached_property import cached_property_with_ttl class Monopoly(object): @cached_property_with_ttl(ttl=5) # cache invalidates after 5 seconds def dice(self): # I dare the reader to implement a game using this method of 'rolling dice'. return random.randint(2,12) ``` Now use it: ```python >>> monopoly = Monopoly() >>> monopoly.dice 10 >>> monopoly.dice 10 >>> from time import sleep >>> sleep(6) # Sleeps long enough to expire the cache >>> monopoly.dice 3 >>> monopoly.dice 3 ``` **Note:** The `ttl` tools do not reliably allow the clearing of the cache. This is why they are broken out into seperate tools. See https://github.com/pydanny/cached-property/issues/16. ## Credits * Pip, Django, Werkzeug, Bottle, Pyramid, and Zope for having their own implementations. This package originally used an implementation that matched the Bottle version. * Reinout Van Rees for pointing out the `cached_property` decorator to me. * 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. * @tinche for pointing out the threading issue and providing a solution. * @bcho for providing the time-to-expire feature # History ## 2.0.1 (2024-10-25) * Via `python_requires` specifies that cached_property is for Python version 3.8 or higher * Officiall drop support for Python 2.6 ## 2.0.0 (2024-10-25) * Remove support for Python versions < 3.8 * Add formal support for Python versions up to 3.13 * Switch to Markdown for docs * Migrate from black to ruff ## 1.5.2 (2020-09-21) * Add formal support for Python 3.8 * Remove formal support for Python 3.4 * Switch from Travis to GitHub actions * Made tests pass flake8 for Python 2.7 ## 1.5.1 (2018-08-05) * Added formal support for Python 3.7 * Removed formal support for Python 3.3 ## 1.4.3 (2018-06-14) * Catch SyntaxError from asyncio import on older versions of Python, thanks to @asottile ## 1.4.2 (2018-04-08) * Really fixed tests, thanks to @pydanny ## 1.4.1 (2018-04-08) * Added conftest.py to manifest so tests work properly off the tarball, thanks to @dotlambda * Ensured new asyncio tests didn't break Python 2.7 builds on Debian, thanks to @pydanny * Code formatting via black, thanks to @pydanny and @ambv ## 1.4.0 (2018-02-25) * Added asyncio support, thanks to @vbraun * Remove Python 2.6 support, whose end of life was 5 years ago, thanks to @pydanny ## 1.3.1 (2017-09-21) * Validate for Python 3.6 ## 1.3.0 (2015-11-24) * Drop some non-ASCII characters from HISTORY.rst, thanks to @AdamWill * Added official support for Python 3.5, thanks to @pydanny and @audreyr * Removed confusingly placed lock from example, thanks to @ionelmc * Corrected invalidation cache documentation, thanks to @proofit404 * Updated to latest Travis-CI environment, thanks to @audreyr ## 1.2.0 (2015-04-28) * Overall code and test refactoring, thanks to @gsakkis * Allow the del statement for resetting cached properties with ttl instead of del obj._cache[attr], thanks to @gsakkis. * Uncovered a bug in PyPy, https://bitbucket.org/pypy/pypy/issue/2033/attributeerror-object-attribute-is-read, thanks to @gsakkis * Fixed threaded_cached_property_with_ttl to actually be thread-safe, thanks to @gsakkis ## 1.1.0 (2015-04-04) * 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 * Fixed typo in README, thanks to @zoidbergwill ## 1.0.0 (2015-02-13) * Added timed to expire feature to `cached_property` decorator. * **Backwards incompatiblity**: Changed `del monopoly.boardwalk` to `del monopoly['boardwalk']` in order to support the new TTL feature. ## 0.1.5 (2014-05-20) * Added threading support with new `threaded_cached_property` decorator * Documented cache invalidation * Updated credits * Sourced the bottle implementation ## 0.1.4 (2014-05-17) * Fix the dang-blarged py_modules argument. ## 0.1.3 (2014-05-17) * Removed import of package into `setup.py` ## 0.1.2 (2014-05-17) * Documentation fixes. Not opening up a RTFD instance for this because it's so simple to use. ## 0.1.1 (2014-05-17) * setup.py fix. Whoops! ## 0.1.0 (2014-05-17) * First release on PyPI. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729871009.0 cached_property-2.0.1/README.md0000644000076500000240000001404114706736241014655 0ustar00drgstaff# cached-property [![Github Actions status](https://github.com/pydanny/cached-property/workflows/Python%20package/badge.svg)](https://github.com/pydanny/cached-property/actions) [![PyPI](https://img.shields.io/pypi/v/cached-property.svg)](https://pypi.python.org/pypi/cached-property) [![Code style: ruff](https://img.shields.io/badge/code%20style-ruff-000000.svg)](https://github.com/astral-sh/ruff) A decorator for caching properties in classes. ## Why? * Makes caching of time or computational expensive properties quick and easy. * Because I got tired of copy/pasting this code from non-web project to non-web project. * I needed something really simple that worked in Python 2 and 3. (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).) ## How to use it Let's define a class with an expensive property. Every time you stay there the price goes up by $50! ```python class Monopoly: def __init__(self): self.boardwalk_price = 500 @property def boardwalk(self): # In reality, this might represent a database call or time # intensive task like calling a third-party API. self.boardwalk_price += 50 return self.boardwalk_price ``` Now run it: ```python >>> monopoly = Monopoly() >>> monopoly.boardwalk 550 >>> monopoly.boardwalk 600 ``` Let's convert the boardwalk property into a `cached_property`. ```python from cached_property import cached_property class Monopoly(object): def __init__(self): self.boardwalk_price = 500 @cached_property def boardwalk(self): # Again, this is a silly example. Don't worry about it, this is # just an example for clarity. self.boardwalk_price += 50 return self.boardwalk_price ``` Now when we run it the price stays at $550. ```python >>> monopoly = Monopoly() >>> monopoly.boardwalk 550 >>> monopoly.boardwalk 550 >>> monopoly.boardwalk 550 ``` Why doesn't the value of `monopoly.boardwalk` change? Because it's a **cached property**! ## Invalidating the Cache Results of cached functions can be invalidated by outside forces. Let's demonstrate how to force the cache to invalidate: ```python >>> monopoly = Monopoly() >>> monopoly.boardwalk 550 >>> monopoly.boardwalk 550 >>> # invalidate the cache >>> del monopoly.__dict__['boardwalk'] >>> # request the boardwalk property again >>> monopoly.boardwalk 600 >>> monopoly.boardwalk 600 ``` ## Working with Threads What if a whole bunch of people want to stay at Boardwalk all at once? This means using threads, which unfortunately causes problems with the standard `cached_property`. In this case, switch to using the `threaded_cached_property`: ```python from cached_property import threaded_cached_property class Monopoly: def __init__(self): self.boardwalk_price = 500 @threaded_cached_property def boardwalk(self): """threaded_cached_property is really nice for when no one waits for other people to finish their turn and rudely start rolling dice and moving their pieces.""" sleep(1) self.boardwalk_price += 50 return self.boardwalk_price ``` Now use it: ```python >>> from threading import Thread >>> from monopoly import Monopoly >>> monopoly = Monopoly() >>> threads = [] >>> for x in range(10): >>> thread = Thread(target=lambda: monopoly.boardwalk) >>> thread.start() >>> threads.append(thread) >>> for thread in threads: >>> thread.join() >>> self.assertEqual(m.boardwalk, 550) ``` ## Working with async/await The cached property can be async, in which case you have to use await as usual to get the value. Because of the caching, the value is only computed once and then cached: ```python from cached_property import cached_property class Monopoly: def __init__(self): self.boardwalk_price = 500 @cached_property async def boardwalk(self): self.boardwalk_price += 50 return self.boardwalk_price ``` Now use it: ```python >>> async def print_boardwalk(): ... monopoly = Monopoly() ... print(await monopoly.boardwalk) ... print(await monopoly.boardwalk) ... print(await monopoly.boardwalk) >>> import asyncio >>> asyncio.get_event_loop().run_until_complete(print_boardwalk()) 550 550 550 ``` Note that this does not work with threading either, most asyncio objects are not thread-safe. And if you run separate event loops in each thread, the cached version will most likely have the wrong event loop. To summarize, either use cooperative multitasking (event loop) or threading, but not both at the same time. ## Timing out the cache Sometimes you want the price of things to reset after a time. Use the `ttl` versions of `cached_property` and `threaded_cached_property`. ```python import random from cached_property import cached_property_with_ttl class Monopoly(object): @cached_property_with_ttl(ttl=5) # cache invalidates after 5 seconds def dice(self): # I dare the reader to implement a game using this method of 'rolling dice'. return random.randint(2,12) ``` Now use it: ```python >>> monopoly = Monopoly() >>> monopoly.dice 10 >>> monopoly.dice 10 >>> from time import sleep >>> sleep(6) # Sleeps long enough to expire the cache >>> monopoly.dice 3 >>> monopoly.dice 3 ``` **Note:** The `ttl` tools do not reliably allow the clearing of the cache. This is why they are broken out into seperate tools. See https://github.com/pydanny/cached-property/issues/16. ## Credits * Pip, Django, Werkzeug, Bottle, Pyramid, and Zope for having their own implementations. This package originally used an implementation that matched the Bottle version. * Reinout Van Rees for pointing out the `cached_property` decorator to me. * 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. * @tinche for pointing out the threading issue and providing a solution. * @bcho for providing the time-to-expire feature ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1729871022.3849008 cached_property-2.0.1/cached_property.egg-info/0000755000076500000240000000000014706736256020251 5ustar00drgstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729871022.0 cached_property-2.0.1/cached_property.egg-info/PKG-INFO0000644000076500000240000002404114706736256021347 0ustar00drgstaffMetadata-Version: 2.1 Name: cached-property Version: 2.0.1 Summary: A decorator for caching properties in classes. Home-page: https://github.com/pydanny/cached-property Author: Daniel Roy Greenfeld Author-email: daniel@feldroy.com License: BSD Keywords: cached-property Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Natural Language :: English Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Requires-Python: >=3.8 Description-Content-Type: text/markdown License-File: LICENSE License-File: AUTHORS.md # cached-property [![Github Actions status](https://github.com/pydanny/cached-property/workflows/Python%20package/badge.svg)](https://github.com/pydanny/cached-property/actions) [![PyPI](https://img.shields.io/pypi/v/cached-property.svg)](https://pypi.python.org/pypi/cached-property) [![Code style: ruff](https://img.shields.io/badge/code%20style-ruff-000000.svg)](https://github.com/astral-sh/ruff) A decorator for caching properties in classes. ## Why? * Makes caching of time or computational expensive properties quick and easy. * Because I got tired of copy/pasting this code from non-web project to non-web project. * I needed something really simple that worked in Python 2 and 3. (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).) ## How to use it Let's define a class with an expensive property. Every time you stay there the price goes up by $50! ```python class Monopoly: def __init__(self): self.boardwalk_price = 500 @property def boardwalk(self): # In reality, this might represent a database call or time # intensive task like calling a third-party API. self.boardwalk_price += 50 return self.boardwalk_price ``` Now run it: ```python >>> monopoly = Monopoly() >>> monopoly.boardwalk 550 >>> monopoly.boardwalk 600 ``` Let's convert the boardwalk property into a `cached_property`. ```python from cached_property import cached_property class Monopoly(object): def __init__(self): self.boardwalk_price = 500 @cached_property def boardwalk(self): # Again, this is a silly example. Don't worry about it, this is # just an example for clarity. self.boardwalk_price += 50 return self.boardwalk_price ``` Now when we run it the price stays at $550. ```python >>> monopoly = Monopoly() >>> monopoly.boardwalk 550 >>> monopoly.boardwalk 550 >>> monopoly.boardwalk 550 ``` Why doesn't the value of `monopoly.boardwalk` change? Because it's a **cached property**! ## Invalidating the Cache Results of cached functions can be invalidated by outside forces. Let's demonstrate how to force the cache to invalidate: ```python >>> monopoly = Monopoly() >>> monopoly.boardwalk 550 >>> monopoly.boardwalk 550 >>> # invalidate the cache >>> del monopoly.__dict__['boardwalk'] >>> # request the boardwalk property again >>> monopoly.boardwalk 600 >>> monopoly.boardwalk 600 ``` ## Working with Threads What if a whole bunch of people want to stay at Boardwalk all at once? This means using threads, which unfortunately causes problems with the standard `cached_property`. In this case, switch to using the `threaded_cached_property`: ```python from cached_property import threaded_cached_property class Monopoly: def __init__(self): self.boardwalk_price = 500 @threaded_cached_property def boardwalk(self): """threaded_cached_property is really nice for when no one waits for other people to finish their turn and rudely start rolling dice and moving their pieces.""" sleep(1) self.boardwalk_price += 50 return self.boardwalk_price ``` Now use it: ```python >>> from threading import Thread >>> from monopoly import Monopoly >>> monopoly = Monopoly() >>> threads = [] >>> for x in range(10): >>> thread = Thread(target=lambda: monopoly.boardwalk) >>> thread.start() >>> threads.append(thread) >>> for thread in threads: >>> thread.join() >>> self.assertEqual(m.boardwalk, 550) ``` ## Working with async/await The cached property can be async, in which case you have to use await as usual to get the value. Because of the caching, the value is only computed once and then cached: ```python from cached_property import cached_property class Monopoly: def __init__(self): self.boardwalk_price = 500 @cached_property async def boardwalk(self): self.boardwalk_price += 50 return self.boardwalk_price ``` Now use it: ```python >>> async def print_boardwalk(): ... monopoly = Monopoly() ... print(await monopoly.boardwalk) ... print(await monopoly.boardwalk) ... print(await monopoly.boardwalk) >>> import asyncio >>> asyncio.get_event_loop().run_until_complete(print_boardwalk()) 550 550 550 ``` Note that this does not work with threading either, most asyncio objects are not thread-safe. And if you run separate event loops in each thread, the cached version will most likely have the wrong event loop. To summarize, either use cooperative multitasking (event loop) or threading, but not both at the same time. ## Timing out the cache Sometimes you want the price of things to reset after a time. Use the `ttl` versions of `cached_property` and `threaded_cached_property`. ```python import random from cached_property import cached_property_with_ttl class Monopoly(object): @cached_property_with_ttl(ttl=5) # cache invalidates after 5 seconds def dice(self): # I dare the reader to implement a game using this method of 'rolling dice'. return random.randint(2,12) ``` Now use it: ```python >>> monopoly = Monopoly() >>> monopoly.dice 10 >>> monopoly.dice 10 >>> from time import sleep >>> sleep(6) # Sleeps long enough to expire the cache >>> monopoly.dice 3 >>> monopoly.dice 3 ``` **Note:** The `ttl` tools do not reliably allow the clearing of the cache. This is why they are broken out into seperate tools. See https://github.com/pydanny/cached-property/issues/16. ## Credits * Pip, Django, Werkzeug, Bottle, Pyramid, and Zope for having their own implementations. This package originally used an implementation that matched the Bottle version. * Reinout Van Rees for pointing out the `cached_property` decorator to me. * 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. * @tinche for pointing out the threading issue and providing a solution. * @bcho for providing the time-to-expire feature # History ## 2.0.1 (2024-10-25) * Via `python_requires` specifies that cached_property is for Python version 3.8 or higher * Officiall drop support for Python 2.6 ## 2.0.0 (2024-10-25) * Remove support for Python versions < 3.8 * Add formal support for Python versions up to 3.13 * Switch to Markdown for docs * Migrate from black to ruff ## 1.5.2 (2020-09-21) * Add formal support for Python 3.8 * Remove formal support for Python 3.4 * Switch from Travis to GitHub actions * Made tests pass flake8 for Python 2.7 ## 1.5.1 (2018-08-05) * Added formal support for Python 3.7 * Removed formal support for Python 3.3 ## 1.4.3 (2018-06-14) * Catch SyntaxError from asyncio import on older versions of Python, thanks to @asottile ## 1.4.2 (2018-04-08) * Really fixed tests, thanks to @pydanny ## 1.4.1 (2018-04-08) * Added conftest.py to manifest so tests work properly off the tarball, thanks to @dotlambda * Ensured new asyncio tests didn't break Python 2.7 builds on Debian, thanks to @pydanny * Code formatting via black, thanks to @pydanny and @ambv ## 1.4.0 (2018-02-25) * Added asyncio support, thanks to @vbraun * Remove Python 2.6 support, whose end of life was 5 years ago, thanks to @pydanny ## 1.3.1 (2017-09-21) * Validate for Python 3.6 ## 1.3.0 (2015-11-24) * Drop some non-ASCII characters from HISTORY.rst, thanks to @AdamWill * Added official support for Python 3.5, thanks to @pydanny and @audreyr * Removed confusingly placed lock from example, thanks to @ionelmc * Corrected invalidation cache documentation, thanks to @proofit404 * Updated to latest Travis-CI environment, thanks to @audreyr ## 1.2.0 (2015-04-28) * Overall code and test refactoring, thanks to @gsakkis * Allow the del statement for resetting cached properties with ttl instead of del obj._cache[attr], thanks to @gsakkis. * Uncovered a bug in PyPy, https://bitbucket.org/pypy/pypy/issue/2033/attributeerror-object-attribute-is-read, thanks to @gsakkis * Fixed threaded_cached_property_with_ttl to actually be thread-safe, thanks to @gsakkis ## 1.1.0 (2015-04-04) * 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 * Fixed typo in README, thanks to @zoidbergwill ## 1.0.0 (2015-02-13) * Added timed to expire feature to `cached_property` decorator. * **Backwards incompatiblity**: Changed `del monopoly.boardwalk` to `del monopoly['boardwalk']` in order to support the new TTL feature. ## 0.1.5 (2014-05-20) * Added threading support with new `threaded_cached_property` decorator * Documented cache invalidation * Updated credits * Sourced the bottle implementation ## 0.1.4 (2014-05-17) * Fix the dang-blarged py_modules argument. ## 0.1.3 (2014-05-17) * Removed import of package into `setup.py` ## 0.1.2 (2014-05-17) * Documentation fixes. Not opening up a RTFD instance for this because it's so simple to use. ## 0.1.1 (2014-05-17) * setup.py fix. Whoops! ## 0.1.0 (2014-05-17) * First release on PyPI. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729871022.0 cached_property-2.0.1/cached_property.egg-info/SOURCES.txt0000644000076500000240000000064714706736256022144 0ustar00drgstaffAUTHORS.md CONTRIBUTING.md HISTORY.md LICENSE MANIFEST.in README.md cached_property.py setup.cfg setup.py cached_property.egg-info/PKG-INFO cached_property.egg-info/SOURCES.txt cached_property.egg-info/dependency_links.txt cached_property.egg-info/not-zip-safe cached_property.egg-info/top_level.txt tests/__init__.py tests/test_async_cached_property.py tests/test_cached_property.py tests/test_coroutine_cached_property.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729871022.0 cached_property-2.0.1/cached_property.egg-info/dependency_links.txt0000644000076500000240000000000114706736256024317 0ustar00drgstaff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729852386.0 cached_property-2.0.1/cached_property.egg-info/not-zip-safe0000644000076500000240000000000114706671742022475 0ustar00drgstaff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729871022.0 cached_property-2.0.1/cached_property.egg-info/top_level.txt0000644000076500000240000000002014706736256022773 0ustar00drgstaffcached_property ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729871009.0 cached_property-2.0.1/cached_property.py0000644000076500000240000001012114706736241017116 0ustar00drgstaff__author__ = "Daniel Roy Greenfeld" __email__ = "daniel@feldroy.com" __version__ = "2.0.1" __license__ = "BSD" from functools import wraps from time import time import threading import asyncio class cached_property: """ A property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the attribute resets the property. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ # noqa def __init__(self, func): self.__doc__ = getattr(func, "__doc__") self.func = func def __get__(self, obj, cls): if obj is None: return self if asyncio.iscoroutinefunction(self.func): return self._wrap_in_coroutine(obj) value = obj.__dict__[self.func.__name__] = self.func(obj) return value def _wrap_in_coroutine(self, obj): @wraps(obj) def wrapper(): future = asyncio.ensure_future(self.func(obj)) obj.__dict__[self.func.__name__] = future return future return wrapper() class threaded_cached_property: """ A cached_property version for use in environments where multiple threads might concurrently try to access the property. """ def __init__(self, func): self.__doc__ = getattr(func, "__doc__") self.func = func self.lock = threading.RLock() def __get__(self, obj, cls): if obj is None: return self obj_dict = obj.__dict__ name = self.func.__name__ with self.lock: try: # check if the value was computed before the lock was acquired return obj_dict[name] except KeyError: # if not, do the calculation and release the lock return obj_dict.setdefault(name, self.func(obj)) class cached_property_with_ttl: """ A property that is only computed once per instance and then replaces itself with an ordinary attribute. Setting the ttl to a number expresses how long the property will last before being timed out. """ def __init__(self, ttl=None): if callable(ttl): func = ttl ttl = None else: func = None self.ttl = ttl self._prepare_func(func) def __call__(self, func): self._prepare_func(func) return self def __get__(self, obj, cls): if obj is None: return self now = time() obj_dict = obj.__dict__ name = self.__name__ try: value, last_updated = obj_dict[name] except KeyError: pass else: ttl_expired = self.ttl and self.ttl < now - last_updated if not ttl_expired: return value value = self.func(obj) obj_dict[name] = (value, now) return value def __delete__(self, obj): obj.__dict__.pop(self.__name__, None) def __set__(self, obj, value): obj.__dict__[self.__name__] = (value, time()) def _prepare_func(self, func): self.func = func if func: self.__doc__ = func.__doc__ self.__name__ = func.__name__ self.__module__ = func.__module__ # Aliases to make cached_property_with_ttl easier to use cached_property_ttl = cached_property_with_ttl timed_cached_property = cached_property_with_ttl class threaded_cached_property_with_ttl(cached_property_with_ttl): """ A cached_property version for use in environments where multiple threads might concurrently try to access the property. """ def __init__(self, ttl=None): super(threaded_cached_property_with_ttl, self).__init__(ttl) self.lock = threading.RLock() def __get__(self, obj, cls): with self.lock: return super(threaded_cached_property_with_ttl, self).__get__(obj, cls) # Alias to make threaded_cached_property_with_ttl easier to use threaded_cached_property_ttl = threaded_cached_property_with_ttl timed_threaded_cached_property = threaded_cached_property_with_ttl ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1729871022.3856816 cached_property-2.0.1/setup.cfg0000644000076500000240000000007514706736256015227 0ustar00drgstaff[wheel] universal = 0 [egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729871009.0 cached_property-2.0.1/setup.py0000755000076500000240000000371114706736241015115 0ustar00drgstaff#!/usr/bin/env python import os import sys import codecs try: from setuptools import setup except ImportError: from distutils.core import setup __version__ = "2.0.1" def read(fname): return codecs.open( os.path.join(os.path.dirname(__file__), fname), "r", "utf-8" ).read() readme = read("README.md") history = read("HISTORY.md") if sys.argv[-1] == "publish": try: import wheel import twine except: # Yes, this is not how we usually do try/except raise ImportError('Run "pip install wheel twine"') os.system("python setup.py sdist bdist_wheel") os.system("twine upload dist/*") os.system("git tag -a %s -m 'version %s'" % (__version__, __version__)) os.system("git push --tags") sys.exit() setup( name="cached-property", version=__version__, description="A decorator for caching properties in classes.", long_description=readme + "\n\n" + history, long_description_content_type="text/markdown", python_requires=">=3.8", author="Daniel Roy Greenfeld", author_email="daniel@feldroy.com", url="https://github.com/pydanny/cached-property", py_modules=["cached_property"], include_package_data=True, license="BSD", zip_safe=False, keywords="cached-property", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Natural Language :: English", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", ], ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1729871022.3846774 cached_property-2.0.1/tests/0000755000076500000240000000000014706736256014546 5ustar00drgstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729852089.0 cached_property-2.0.1/tests/__init__.py0000644000076500000240000000000014706671271016640 0ustar00drgstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729852089.0 cached_property-2.0.1/tests/test_async_cached_property.py0000644000076500000240000000726314706671271022532 0ustar00drgstaffimport asyncio import time import unittest from threading import Lock, Thread from freezegun import freeze_time import cached_property def CheckFactory(cached_property_decorator, threadsafe=False): """ Create dynamically a Check class whose add_cached method is decorated by the cached_property_decorator. """ class Check: def __init__(self): self.control_total = 0 self.cached_total = 0 self.lock = Lock() async def add_control(self): # noqa self.control_total += 1 return self.control_total @cached_property_decorator async def add_cached(self): if threadsafe: time.sleep(1) # Need to guard this since += isn't atomic. with self.lock: self.cached_total += 1 else: self.cached_total += 1 return self.cached_total def run_threads(self, num_threads): threads = [] for _ in range(num_threads): def call_add_cached(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(self.add_cached) thread = Thread(target=call_add_cached) thread.start() threads.append(thread) for thread in threads: thread.join() return Check class TestCachedProperty(unittest.IsolatedAsyncioTestCase): """Tests for cached_property""" cached_property_factory = cached_property.cached_property async def assert_control(self, check, expected): """ Assert that both `add_control` and 'control_total` equal `expected` """ self.assertEqual(expected, await check.add_control()) self.assertEqual(expected, check.control_total) async def assert_cached(self, check, expected): """ Assert that both `add_cached` and 'cached_total` equal `expected` """ print("assert_cached", check.add_cached) self.assertEqual(expected, await check.add_cached) self.assertEqual(expected, check.cached_total) async def test_cached_property(self): Check = CheckFactory(self.cached_property_factory) check = Check() # The control shows that we can continue to add 1 await self.assert_control(check, 1) await self.assert_control(check, 2) # The cached version demonstrates how nothing is added after the first await self.assert_cached(check, 1) await self.assert_cached(check, 1) # The cache does not expire with freeze_time("9999-01-01"): await self.assert_cached(check, 1) # Typically descriptors return themselves if accessed though the class # rather than through an instance. self.assertTrue(isinstance(Check.add_cached, self.cached_property_factory)) async def test_reset_cached_property(self): Check = CheckFactory(self.cached_property_factory) check = Check() # Run standard cache assertion await self.assert_cached(check, 1) await self.assert_cached(check, 1) # Clear the cache del check.add_cached # Value is cached again after the next access await self.assert_cached(check, 2) await self.assert_cached(check, 2) async def test_none_cached_property(self): class Check: def __init__(self): self.cached_total = None @self.cached_property_factory async def add_cached(self): return self.cached_total await self.assert_cached(Check(), None) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729852089.0 cached_property-2.0.1/tests/test_cached_property.py0000644000076500000240000001350514706671271021331 0ustar00drgstaffimport time import unittest from threading import Lock, Thread from freezegun import freeze_time import cached_property def CheckFactory(cached_property_decorator, threadsafe=False): """ Create dynamically a Check class whose add_cached method is decorated by the cached_property_decorator. """ class Check: def __init__(self): self.control_total = 0 self.cached_total = 0 self.lock = Lock() @property def add_control(self): self.control_total += 1 return self.control_total @cached_property_decorator def add_cached(self): if threadsafe: time.sleep(1) # Need to guard this since += isn't atomic. with self.lock: self.cached_total += 1 else: self.cached_total += 1 return self.cached_total def run_threads(self, num_threads): threads = [] for _ in range(num_threads): thread = Thread(target=self.add_cached) thread.start() threads.append(thread) for thread in threads: thread.join() return Check class TestCachedProperty(unittest.TestCase): """Tests for cached_property""" cached_property_factory = cached_property.cached_property def assert_control(self, check, expected): """ Assert that both `add_control` and 'control_total` equal `expected` """ self.assertEqual(expected, check.add_control) self.assertEqual(expected, check.control_total) def assert_cached(self, check, expected): """ Assert that both `add_cached` and 'cached_total` equal `expected` """ self.assertEqual(expected, check.add_cached) self.assertEqual(expected, check.cached_total) def test_cached_property(self): Check = CheckFactory(self.cached_property_factory) check = Check() # The control shows that we can continue to add 1 self.assert_control(check, 1) self.assert_control(check, 2) # The cached version demonstrates how nothing is added after the first self.assert_cached(check, 1) self.assert_cached(check, 1) # The cache does not expire with freeze_time("9999-01-01"): self.assert_cached(check, 1) # Typically descriptors return themselves if accessed though the class # rather than through an instance. self.assertTrue(isinstance(Check.add_cached, self.cached_property_factory)) def test_reset_cached_property(self): Check = CheckFactory(self.cached_property_factory) check = Check() # Run standard cache assertion self.assert_cached(check, 1) self.assert_cached(check, 1) # Clear the cache del check.add_cached # Value is cached again after the next access self.assert_cached(check, 2) self.assert_cached(check, 2) def test_none_cached_property(self): class Check: def __init__(self): self.cached_total = None @self.cached_property_factory def add_cached(self): return self.cached_total self.assert_cached(Check(), None) def test_set_cached_property(self): Check = CheckFactory(self.cached_property_factory) check = Check() check.add_cached = "foo" self.assertEqual("foo", check.add_cached) self.assertEqual(0, check.cached_total) class TestThreadedCachedProperty(TestCachedProperty): """Tests for threaded_cached_property""" cached_property_factory = cached_property.threaded_cached_property def test_threads(self): Check = CheckFactory(self.cached_property_factory, threadsafe=True) check = Check() num_threads = 5 # threaded_cached_property_with_ttl is thread-safe check.run_threads(num_threads) self.assert_cached(check, 1) self.assert_cached(check, 1) # The cache does not expire with freeze_time("9999-01-01"): check.run_threads(num_threads) self.assert_cached(check, 1) self.assert_cached(check, 1) class TestCachedPropertyWithTTL(TestCachedProperty): """Tests for cached_property_with_ttl""" cached_property_factory = cached_property.cached_property_with_ttl def test_ttl_expiry(self): Check = CheckFactory(self.cached_property_factory(ttl=100000)) check = Check() # Run standard cache assertion self.assert_cached(check, 1) self.assert_cached(check, 1) # The cache expires in the future with freeze_time("9999-01-01"): self.assert_cached(check, 2) self.assert_cached(check, 2) # Things are not reverted when we are back to the present self.assert_cached(check, 2) self.assert_cached(check, 2) class TestThreadedCachedPropertyWithTTL( TestThreadedCachedProperty, TestCachedPropertyWithTTL ): """Tests for threaded_cached_property_with_ttl""" cached_property_factory = cached_property.threaded_cached_property_with_ttl def test_threads_ttl_expiry(self): Check = CheckFactory(self.cached_property_factory(ttl=100000), threadsafe=True) check = Check() num_threads = 5 # Same as in test_threads check.run_threads(num_threads) self.assert_cached(check, 1) self.assert_cached(check, 1) # The cache expires in the future with freeze_time("9999-01-01"): check.run_threads(num_threads) self.assert_cached(check, 2) self.assert_cached(check, 2) # Things are not reverted when we are back to the present self.assert_cached(check, 2) self.assert_cached(check, 2) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729852089.0 cached_property-2.0.1/tests/test_coroutine_cached_property.py0000644000076500000240000000617014706671271023420 0ustar00drgstaff""" The same tests as in :mod:`.test_async_cached_property`, but with the old yield from instead of the new async/await syntax. Used to test Python 3.4 compatibility which has asyncio but doesn't have async/await yet. """ import unittest from freezegun import freeze_time import cached_property def CheckFactory(cached_property_decorator): """ Create dynamically a Check class whose add_cached method is decorated by the cached_property_decorator. """ class Check: def __init__(self): self.control_total = 0 self.cached_total = 0 async def add_control(self): self.control_total += 1 return self.control_total @cached_property_decorator async def add_cached(self): self.cached_total += 1 return self.cached_total return Check class TestCachedProperty(unittest.IsolatedAsyncioTestCase): """Tests for cached_property""" cached_property_factory = cached_property.cached_property async def assert_control(self, check, expected): """ Assert that both `add_control` and 'control_total` equal `expected` """ value = yield check.add_control() self.assertEqual(expected, value) self.assertEqual(expected, check.control_total) async def assert_cached(self, check, expected): """ Assert that both `add_cached` and 'cached_total` equal `expected` """ print("assert_cached", check.add_cached) value = yield check.add_cached self.assertEqual(expected, value) self.assertEqual(expected, check.cached_total) async def test_cached_property(self): Check = CheckFactory(self.cached_property_factory) check = Check() # The control shows that we can continue to add 1 yield self.assert_control(check, 1) yield self.assert_control(check, 2) # The cached version demonstrates how nothing is added after the first yield self.assert_cached(check, 1) yield self.assert_cached(check, 1) # The cache does not expire with freeze_time("9999-01-01"): yield self.assert_cached(check, 1) # Typically descriptors return themselves if accessed though the class # rather than through an instance. self.assertTrue(isinstance(Check.add_cached, self.cached_property_factory)) async def test_reset_cached_property(self): Check = CheckFactory(self.cached_property_factory) check = Check() # Run standard cache assertion yield self.assert_cached(check, 1) yield self.assert_cached(check, 1) # Clear the cache del check.add_cached # Value is cached again after the next access yield self.assert_cached(check, 2) yield self.assert_cached(check, 2) async def test_none_cached_property(self): class Check: def __init__(self): self.cached_total = None @self.cached_property_factory async def add_cached(self): return self.cached_total yield self.assert_cached(Check(), None)