cached-property-1.3.0/0000755000076600000240000000000012625211722015041 5ustar dannystaff00000000000000cached-property-1.3.0/AUTHORS.rst0000644000076600000240000000056412625211053016722 0ustar dannystaff00000000000000======= Credits ======= Development Lead ---------------- * Daniel Roy Greenfeld * Audrey Roy Greenfeld (@audreyr) Contributors ------------ * Tin Tvrtković * @bcho * George Sakkis (@gsakkis) * Adam Williamson * Ionel Cristian Mărieș (@ionelmc) * Malyshev Artem (@proofit404) cached-property-1.3.0/cached_property.egg-info/0000755000076600000240000000000012625211722021706 5ustar dannystaff00000000000000cached-property-1.3.0/cached_property.egg-info/dependency_links.txt0000644000076600000240000000000112625211722025754 0ustar dannystaff00000000000000 cached-property-1.3.0/cached_property.egg-info/not-zip-safe0000644000076600000240000000000112517733264024146 0ustar dannystaff00000000000000 cached-property-1.3.0/cached_property.egg-info/PKG-INFO0000644000076600000240000002375512625211722023017 0ustar dannystaff00000000000000Metadata-Version: 1.1 Name: cached-property Version: 1.3.0 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://img.shields.io/travis/pydanny/cached-property/master.svg :target: https://travis-ci.org/pydanny/cached-property 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) 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 uses an implementation that matches 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 History ------- 1.3.0 (2015-11-24) ++++++++++++++++++ * 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.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 cached-property-1.3.0/cached_property.egg-info/SOURCES.txt0000644000076600000240000000053712625211722023577 0ustar dannystaff00000000000000AUTHORS.rst CONTRIBUTING.rst HISTORY.rst LICENSE MANIFEST.in README.rst 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_cached_property.pycached-property-1.3.0/cached_property.egg-info/top_level.txt0000644000076600000240000000002012625211722024430 0ustar dannystaff00000000000000cached_property cached-property-1.3.0/cached_property.py0000644000076600000240000000747412625211534020603 0ustar dannystaff00000000000000# -*- coding: utf-8 -*- __author__ = 'Daniel Greenfeld' __email__ = 'pydanny@gmail.com' __version__ = '1.3.0' __license__ = 'BSD' from time import time import threading 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 value = obj.__dict__[self.func.__name__] = self.func(obj) return value 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 cached-property-1.3.0/CONTRIBUTING.rst0000644000076600000240000000625712517732750017525 0ustar dannystaff00000000000000============ 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. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: $ flake8 cached-property tests $ python setup.py test $ tox To get flake8 and tox, just pip install them into your virtualenv. 6. 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 7. 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.6, 2.7, and 3.3, 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-propertycached-property-1.3.0/HISTORY.rst0000644000076600000240000000354612625211053016741 0ustar dannystaff00000000000000.. :changelog: History ------- 1.3.0 (2015-11-24) ++++++++++++++++++ * 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. cached-property-1.3.0/LICENSE0000644000076600000240000000270712517732750016065 0ustar dannystaff00000000000000Copyright (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. cached-property-1.3.0/MANIFEST.in0000644000076600000240000000036312517732750016612 0ustar dannystaff00000000000000include AUTHORS.rst include CONTRIBUTING.rst include HISTORY.rst include LICENSE include README.rst recursive-include tests * recursive-exclude * __pycache__ recursive-exclude * *.py[co] recursive-include docs *.rst conf.py Makefile make.batcached-property-1.3.0/PKG-INFO0000644000076600000240000002375512625211722016152 0ustar dannystaff00000000000000Metadata-Version: 1.1 Name: cached-property Version: 1.3.0 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://img.shields.io/travis/pydanny/cached-property/master.svg :target: https://travis-ci.org/pydanny/cached-property 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) 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 uses an implementation that matches 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 History ------- 1.3.0 (2015-11-24) ++++++++++++++++++ * 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.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 cached-property-1.3.0/README.rst0000644000076600000240000001244112625211534016533 0ustar dannystaff00000000000000=============================== cached-property =============================== .. image:: https://img.shields.io/pypi/v/cached-property.svg :target: https://pypi.python.org/pypi/cached-property .. image:: https://img.shields.io/travis/pydanny/cached-property/master.svg :target: https://travis-ci.org/pydanny/cached-property 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) 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 uses an implementation that matches 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 cached-property-1.3.0/setup.cfg0000644000076600000240000000012212625211722016655 0ustar dannystaff00000000000000[wheel] universal = 1 [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 cached-property-1.3.0/setup.py0000755000076600000240000000272412625211534016564 0ustar dannystaff00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup __version__ = '1.3.0' readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') if sys.argv[-1] == 'publish': os.system('python setup.py sdist bdist_wheel upload') 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, 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.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], ) cached-property-1.3.0/tests/0000755000076600000240000000000012625211722016203 5ustar dannystaff00000000000000cached-property-1.3.0/tests/__init__.py0000644000076600000240000000003012517732750020316 0ustar dannystaff00000000000000# -*- coding: utf-8 -*- cached-property-1.3.0/tests/test_cached_property.py0000644000076600000240000001726012517732750023006 0ustar dannystaff00000000000000# -*- 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)