
Security News
How Enterprise Security Is Adapting to AI-Accelerated Threats
Socket CTO Ahmad Nassri discusses why supply chain attacks now target developer machines and what AI means for the future of enterprise security.
property-cached
Advanced tools
.. image:: https://img.shields.io/travis/althonos/property-cached/master.svg?style=flat-square :target: https://travis-ci.org/althonos/property-cached
.. image:: https://img.shields.io/codecov/c/gh/althonos/property-cached.svg?style=flat-square :target: https://codecov.io/gh/althonos/property-cached
.. image:: https://img.shields.io/pypi/v/property-cached.svg?style=flat-square :target: https://pypi.python.org/pypi/property-cached
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg?style=flat-square :target: https://github.com/ambv/black
A decorator for caching properties in classes (forked from cached-property).
This library was forked from the upstream library cached-property since its
developer does not seem to be maintaining it anymore. It works as a drop-in
replacement with fully compatible API (import property_cached instead of
cached_property in your code and voilà). In case development resumes on
the original library, this one is likely to be deprecated.
Slightly modified README included below:
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!
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
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)
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.
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.
@pydanny for the original cached-property implementation.cached_property decorator to me.@audreyr_ who created cookiecutter_, which meant rolling this out took @pydanny 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
.. :changelog:
1.6.4 (2020-03-06) ++++++++++++++++++
#25 <https://github.com/althonos/property-cached/pull/25>_)1.6.3 (2019-09-07) ++++++++++++++++++
cached_property docstring not showing (#171 <https://github.com/pydanny/cached-property/pull/171>_).1.6.2 (2019-07-22) ++++++++++++++++++
1.6.1 (2019-07-22) ++++++++++++++++++
setup.cfg1.6.0 (2019-07-22) ++++++++++++++++++
cached_property now inherits from property__dict__functools.update_wrapper__set_name__ magic method available since Python 3.61.5.1 (2018-08-05) ++++++++++++++++++
1.4.3 (2018-06-14) +++++++++++++++++++
1.4.2 (2018-04-08) ++++++++++++++++++
1.4.1 (2018-04-08) ++++++++++++++++++
1.4.0 (2018-02-25) ++++++++++++++++++
1.3.1 (2017-09-21) ++++++++++++++++++
1.3.0 (2015-11-24) ++++++++++++++++++
1.2.0 (2015-04-28) ++++++++++++++++++
1.1.0 (2015-04-04) ++++++++++++++++++
1.0.0 (2015-02-13) ++++++++++++++++++
cached_property decorator.del monopoly.boardwalk to del monopoly['boardwalk'] in order to support the new TTL feature.0.1.5 (2014-05-20) ++++++++++++++++++
threaded_cached_property decorator0.1.4 (2014-05-17) ++++++++++++++++++
0.1.3 (2014-05-17) ++++++++++++++++++
setup.py0.1.2 (2014-05-17) ++++++++++++++++++
0.1.1 (2014-05-17) ++++++++++++++++++
0.1.0 (2014-05-17) ++++++++++++++++++
FAQs
A decorator for caching properties in classes (forked from cached-property).
We found that property-cached demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Socket CTO Ahmad Nassri discusses why supply chain attacks now target developer machines and what AI means for the future of enterprise security.

Security News
Learn the essential steps every developer should take to stay secure on npm and reduce exposure to supply chain attacks.

Security News
Experts push back on new claims about AI-driven ransomware, warning that hype and sponsored research are distorting how the threat is understood.