././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1600713539.5385096 cached-property-1.5.2/0000755000076500000240000000000000000000000014510 5ustar00drgstaff00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600710749.0 cached-property-1.5.2/AUTHORS.rst0000644000076500000240000000063600000000000016374 0ustar00drgstaff00000000000000======= Credits ======= Development Lead ---------------- * Daniel Roy Greenfeld (@pydanny) * Audrey Roy Greenfeld (@audreyr) Contributors ------------ * Tin Tvrtković * @bcho * George Sakkis (@gsakkis) * Adam Williamson * Ionel Cristian Mărieș (@ionelmc) * Malyshev Artem (@proofit404) * Volker Braun (@vbraun) * Qudus Oladipo (@stikks) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600710749.0 cached-property-1.5.2/CONTRIBUTING.rst0000644000076500000240000000635700000000000017164 0ustar00drgstaff00000000000000============ 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:: $ 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:: $ mkvirtualenv cached-property $ cd cached-property/ $ python setup.py develop 4. Create a branch for local development:: $ 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.6):: $ pip install -U black $ black . 6. When you're done making changes, check that your changes pass the tests, including testing other Python versions with tox:: $ pytest tests/ $ tox To get tox, just pip install it into your virtualenv. 7. Commit your changes and push your branch to GitHub:: $ 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.rst. 3. The pull request should work for Python 2.7, and 3.3, 3.4, 3.5, 3.6 and for PyPy. Check https://travis-ci.org/pydanny/cached-property/pull_requests and make sure that the tests pass for all supported Python versions. Tips ---- To run a subset of tests:: $ python -m unittest tests.test_cached-property ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600713372.0 cached-property-1.5.2/HISTORY.rst0000644000076500000240000000567400000000000016417 0ustar00drgstaff00000000000000.. :changelog: History ------- 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. ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600710749.0 cached-property-1.5.2/LICENSE0000644000076500000240000000270700000000000015523 0ustar00drgstaff00000000000000Copyright (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. ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600710749.0 cached-property-1.5.2/MANIFEST.in0000644000076500000240000000041400000000000016245 0ustar00drgstaff00000000000000include AUTHORS.rst include CONTRIBUTING.rst include HISTORY.rst include LICENSE include README.rst recursive-include tests * include conftest.py recursive-exclude * __pycache__ recursive-exclude * *.py[co] recursive-include docs *.rst conftest.py Makefile make.bat ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1600713539.5387163 cached-property-1.5.2/PKG-INFO0000644000076500000240000003367500000000000015623 0ustar00drgstaff00000000000000Metadata-Version: 2.1 Name: cached-property Version: 1.5.2 Summary: A decorator for caching properties in classes. Home-page: https://github.com/pydanny/cached-property Author: Daniel Greenfeld Author-email: pydanny@gmail.com License: BSD Description: =============================== cached-property =============================== .. image:: https://img.shields.io/pypi/v/cached-property.svg :target: https://pypi.python.org/pypi/cached-property .. image:: https://github.com/pydanny/cached-property/workflows/Python%20package/badge.svg :target: https://github.com/pydanny/cached-property/actions .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black :alt: Code style: black 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. How to use it -------------- Let's define a class with an expensive property. Every time you stay there the price goes up by $50! .. code-block:: python class Monopoly(object): 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: .. code-block:: python >>> monopoly = Monopoly() >>> monopoly.boardwalk 550 >>> monopoly.boardwalk 600 Let's convert the boardwalk property into a ``cached_property``. .. code-block:: 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. .. code-block:: 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: .. code-block:: 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``: .. code-block:: python from cached_property import threaded_cached_property class Monopoly(object): 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: .. code-block:: 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 (Python 3.5+) -------------------------------------- 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: .. code-block:: python from cached_property import cached_property class Monopoly(object): def __init__(self): self.boardwalk_price = 500 @cached_property async def boardwalk(self): self.boardwalk_price += 50 return self.boardwalk_price Now use it: .. code-block:: 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``. .. code-block:: 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: .. code-block:: 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, Werkzueg, 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 `@audreyr`_ who created `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 .. _`@audreyr`: https://github.com/audreyr .. _`cookiecutter`: https://github.com/audreyr/cookiecutter Support This Project --------------------------- This project is maintained by volunteers. Support their efforts by spreading the word about: Django Crash Course ++++++++++++++++++++++++++++++++++++ .. image:: https://cdn.shopify.com/s/files/1/0304/6901/files/Django-Crash-Course-300x436.jpg :name: Django Crash Course: Covers Django 3.0 and Python 3.8 :align: center :alt: Django Crash Course :target: https://www.roygreenfeld.com/products/django-crash-course Django Crash Course for Django 3.0 and Python 3.8 is the best cheese-themed Django reference in the universe! History ------- 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. Keywords: cached-property Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Natural Language :: English Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Description-Content-Type: text/x-rst ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600713376.0 cached-property-1.5.2/README.rst0000644000076500000240000001640600000000000016206 0ustar00drgstaff00000000000000=============================== cached-property =============================== .. image:: https://img.shields.io/pypi/v/cached-property.svg :target: https://pypi.python.org/pypi/cached-property .. image:: https://github.com/pydanny/cached-property/workflows/Python%20package/badge.svg :target: https://github.com/pydanny/cached-property/actions .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black :alt: Code style: black 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. How to use it -------------- Let's define a class with an expensive property. Every time you stay there the price goes up by $50! .. code-block:: python class Monopoly(object): 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: .. code-block:: python >>> monopoly = Monopoly() >>> monopoly.boardwalk 550 >>> monopoly.boardwalk 600 Let's convert the boardwalk property into a ``cached_property``. .. code-block:: 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. .. code-block:: 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: .. code-block:: 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``: .. code-block:: python from cached_property import threaded_cached_property class Monopoly(object): 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: .. code-block:: 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 (Python 3.5+) -------------------------------------- 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: .. code-block:: python from cached_property import cached_property class Monopoly(object): def __init__(self): self.boardwalk_price = 500 @cached_property async def boardwalk(self): self.boardwalk_price += 50 return self.boardwalk_price Now use it: .. code-block:: 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``. .. code-block:: 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: .. code-block:: 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, Werkzueg, 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 `@audreyr`_ who created `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 .. _`@audreyr`: https://github.com/audreyr .. _`cookiecutter`: https://github.com/audreyr/cookiecutter Support This Project --------------------------- This project is maintained by volunteers. Support their efforts by spreading the word about: Django Crash Course ++++++++++++++++++++++++++++++++++++ .. image:: https://cdn.shopify.com/s/files/1/0304/6901/files/Django-Crash-Course-300x436.jpg :name: Django Crash Course: Covers Django 3.0 and Python 3.8 :align: center :alt: Django Crash Course :target: https://www.roygreenfeld.com/products/django-crash-course Django Crash Course for Django 3.0 and Python 3.8 is the best cheese-themed Django reference in the universe! ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1600713539.5368838 cached-property-1.5.2/cached_property.egg-info/0000755000076500000240000000000000000000000021355 5ustar00drgstaff00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600713539.0 cached-property-1.5.2/cached_property.egg-info/PKG-INFO0000644000076500000240000003367500000000000022470 0ustar00drgstaff00000000000000Metadata-Version: 2.1 Name: cached-property Version: 1.5.2 Summary: A decorator for caching properties in classes. Home-page: https://github.com/pydanny/cached-property Author: Daniel Greenfeld Author-email: pydanny@gmail.com License: BSD Description: =============================== cached-property =============================== .. image:: https://img.shields.io/pypi/v/cached-property.svg :target: https://pypi.python.org/pypi/cached-property .. image:: https://github.com/pydanny/cached-property/workflows/Python%20package/badge.svg :target: https://github.com/pydanny/cached-property/actions .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black :alt: Code style: black 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. How to use it -------------- Let's define a class with an expensive property. Every time you stay there the price goes up by $50! .. code-block:: python class Monopoly(object): 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: .. code-block:: python >>> monopoly = Monopoly() >>> monopoly.boardwalk 550 >>> monopoly.boardwalk 600 Let's convert the boardwalk property into a ``cached_property``. .. code-block:: 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. .. code-block:: 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: .. code-block:: 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``: .. code-block:: python from cached_property import threaded_cached_property class Monopoly(object): 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: .. code-block:: 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 (Python 3.5+) -------------------------------------- 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: .. code-block:: python from cached_property import cached_property class Monopoly(object): def __init__(self): self.boardwalk_price = 500 @cached_property async def boardwalk(self): self.boardwalk_price += 50 return self.boardwalk_price Now use it: .. code-block:: 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``. .. code-block:: 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: .. code-block:: 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, Werkzueg, 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 `@audreyr`_ who created `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 .. _`@audreyr`: https://github.com/audreyr .. _`cookiecutter`: https://github.com/audreyr/cookiecutter Support This Project --------------------------- This project is maintained by volunteers. Support their efforts by spreading the word about: Django Crash Course ++++++++++++++++++++++++++++++++++++ .. image:: https://cdn.shopify.com/s/files/1/0304/6901/files/Django-Crash-Course-300x436.jpg :name: Django Crash Course: Covers Django 3.0 and Python 3.8 :align: center :alt: Django Crash Course :target: https://www.roygreenfeld.com/products/django-crash-course Django Crash Course for Django 3.0 and Python 3.8 is the best cheese-themed Django reference in the universe! History ------- 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. Keywords: cached-property Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Natural Language :: English Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Description-Content-Type: text/x-rst ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600713539.0 cached-property-1.5.2/cached_property.egg-info/SOURCES.txt0000644000076500000240000000066700000000000023252 0ustar00drgstaff00000000000000AUTHORS.rst CONTRIBUTING.rst HISTORY.rst LICENSE MANIFEST.in README.rst cached_property.py conftest.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././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600713539.0 cached-property-1.5.2/cached_property.egg-info/dependency_links.txt0000644000076500000240000000000100000000000025423 0ustar00drgstaff00000000000000 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600712973.0 cached-property-1.5.2/cached_property.egg-info/not-zip-safe0000644000076500000240000000000100000000000023603 0ustar00drgstaff00000000000000 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600713539.0 cached-property-1.5.2/cached_property.egg-info/top_level.txt0000644000076500000240000000002000000000000024077 0ustar00drgstaff00000000000000cached_property ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600712714.0 cached-property-1.5.2/cached_property.py0000644000076500000240000001034400000000000020237 0ustar00drgstaff00000000000000# -*- coding: utf-8 -*- __author__ = "Daniel Greenfeld" __email__ = "pydanny@gmail.com" __version__ = "1.5.2" __license__ = "BSD" from functools import wraps from time import time import threading try: import asyncio except (ImportError, SyntaxError): asyncio = None class cached_property(object): """ 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 and 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) @asyncio.coroutine def wrapper(): future = asyncio.ensure_future(self.func(obj)) obj.__dict__[self.func.__name__] = future return future return wrapper() class threaded_cached_property(object): """ 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(object): """ 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 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600710749.0 cached-property-1.5.2/conftest.py0000644000076500000240000000074600000000000016716 0ustar00drgstaff00000000000000 import sys # Whether "import asyncio" works has_asyncio = sys.version_info[0] == 3 and sys.version_info[1] >= 4 # Whether the async and await keywords work has_async_await = sys.version_info[0] == 3 and sys.version_info[1] >= 5 print("conftest.py", has_asyncio, has_async_await) collect_ignore = [] if not has_asyncio: collect_ignore.append("tests/test_coroutine_cached_property.py") if not has_async_await: collect_ignore.append("tests/test_async_cached_property.py") ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1600713539.5391505 cached-property-1.5.2/setup.cfg0000644000076500000240000000007500000000000016333 0ustar00drgstaff00000000000000[wheel] universal = 1 [egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600713534.0 cached-property-1.5.2/setup.py0000755000076500000240000000351700000000000016233 0ustar00drgstaff00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import codecs try: from setuptools import setup except ImportError: from distutils.core import setup __version__ = "1.5.2" def read(fname): return codecs.open( os.path.join(os.path.dirname(__file__), fname), "r", "utf-8" ).read() readme = read("README.rst") history = read("HISTORY.rst").replace(".. :changelog:", "") 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/x-rst", author="Daniel Greenfeld", author_email="pydanny@gmail.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 :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", ], ) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1600713539.5382771 cached-property-1.5.2/tests/0000755000076500000240000000000000000000000015652 5ustar00drgstaff00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600710749.0 cached-property-1.5.2/tests/__init__.py0000644000076500000240000000003000000000000017754 0ustar00drgstaff00000000000000# -*- coding: utf-8 -*- ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600710749.0 cached-property-1.5.2/tests/test_async_cached_property.py0000644000076500000240000000777500000000000023653 0ustar00drgstaff00000000000000# -*- coding: utf-8 -*- import asyncio import time import unittest from threading import Lock, Thread from freezegun import freeze_time import cached_property def unittest_run_loop(f): def wrapper(*args, **kwargs): coro = asyncio.coroutine(f) future = coro(*args, **kwargs) loop = asyncio.get_event_loop() loop.run_until_complete(future) return wrapper 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(object): 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.TestCase): """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(await check.add_control(), expected) self.assertEqual(check.control_total, expected) 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(await check.add_cached, expected) self.assertEqual(check.cached_total, expected) @unittest_run_loop 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)) @unittest_run_loop 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) @unittest_run_loop async def test_none_cached_property(self): class Check(object): 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) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600710749.0 cached-property-1.5.2/tests/test_cached_property.py0000644000076500000240000001705700000000000022450 0ustar00drgstaff00000000000000# -*- coding: utf-8 -*- 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(object): 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=lambda: 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(check.add_control, expected) self.assertEqual(check.control_total, expected) def assert_cached(self, check, expected): """ Assert that both `add_cached` and 'cached_total` equal `expected` """ self.assertEqual(check.add_cached, expected) self.assertEqual(check.cached_total, expected) 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(object): 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(check.add_cached, "foo") self.assertEqual(check.cached_total, 0) def test_threads(self): Check = CheckFactory(self.cached_property_factory, threadsafe=True) check = Check() num_threads = 5 # cached_property_with_ttl is *not* thread-safe! check.run_threads(num_threads) # This assertion hinges on the fact the system executing the test can # spawn and start running num_threads threads within the sleep period # (defined in the Check class as 1 second). If num_threads were to be # massively increased (try 10000), the actual value returned would be # between 1 and num_threads, depending on thread scheduling and # preemption. self.assert_cached(check, num_threads) self.assert_cached(check, num_threads) # The cache does not expire with freeze_time("9999-01-01"): check.run_threads(num_threads) self.assert_cached(check, num_threads) self.assert_cached(check, num_threads) 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) 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, num_threads) self.assert_cached(check, num_threads) # The cache expires in the future with freeze_time("9999-01-01"): check.run_threads(num_threads) self.assert_cached(check, 2 * num_threads) self.assert_cached(check, 2 * num_threads) # Things are not reverted when we are back to the present self.assert_cached(check, 2 * num_threads) self.assert_cached(check, 2 * num_threads) 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) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600710749.0 cached-property-1.5.2/tests/test_coroutine_cached_property.py0000644000076500000240000000725600000000000024537 0ustar00drgstaff00000000000000# -*- coding: utf-8 -*- """ 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 import asyncio from freezegun import freeze_time import cached_property def unittest_run_loop(f): def wrapper(*args, **kwargs): coro = asyncio.coroutine(f) future = coro(*args, **kwargs) loop = asyncio.get_event_loop() loop.run_until_complete(future) return wrapper def CheckFactory(cached_property_decorator): """ Create dynamically a Check class whose add_cached method is decorated by the cached_property_decorator. """ class Check(object): def __init__(self): self.control_total = 0 self.cached_total = 0 @asyncio.coroutine def add_control(self): self.control_total += 1 return self.control_total @cached_property_decorator @asyncio.coroutine def add_cached(self): self.cached_total += 1 return self.cached_total return Check class TestCachedProperty(unittest.TestCase): """Tests for cached_property""" cached_property_factory = cached_property.cached_property @asyncio.coroutine def assert_control(self, check, expected): """ Assert that both `add_control` and 'control_total` equal `expected` """ value = yield from check.add_control() # noqa self.assertEqual(value, expected) self.assertEqual(check.control_total, expected) @asyncio.coroutine def assert_cached(self, check, expected): """ Assert that both `add_cached` and 'cached_total` equal `expected` """ print("assert_cached", check.add_cached) value = yield from check.add_cached self.assertEqual(value, expected) self.assertEqual(check.cached_total, expected) @unittest_run_loop @asyncio.coroutine def test_cached_property(self): Check = CheckFactory(self.cached_property_factory) check = Check() # The control shows that we can continue to add 1 yield from self.assert_control(check, 1) yield from self.assert_control(check, 2) # The cached version demonstrates how nothing is added after the first yield from self.assert_cached(check, 1) yield from self.assert_cached(check, 1) # The cache does not expire with freeze_time("9999-01-01"): yield from 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)) @unittest_run_loop @asyncio.coroutine def test_reset_cached_property(self): Check = CheckFactory(self.cached_property_factory) check = Check() # Run standard cache assertion yield from self.assert_cached(check, 1) yield from self.assert_cached(check, 1) # Clear the cache del check.add_cached # Value is cached again after the next access yield from self.assert_cached(check, 2) yield from self.assert_cached(check, 2) @unittest_run_loop @asyncio.coroutine def test_none_cached_property(self): class Check(object): def __init__(self): self.cached_total = None @self.cached_property_factory @asyncio.coroutine def add_cached(self): return self.cached_total yield from self.assert_cached(Check(), None)