python-cached-property
Subpackage Descriptions
single |
# cached-property
[Github Actions status]
[PyPI]
[![Code style: ruff]](https://github.com/astral-sh/ruff)
A decorator for caching properties in classes.
## Why?
* Makes caching of time or computational expensive properties quick and
easy.
* Because I got tired of copy/pasting this code from non-web project to
non-web project.
* I needed something really simple that worked in Python 2 and 3.
(Python 3.8 added a version of this decorator as
[`@functools.cached_property`].)
## How to use it
Let's define a class with an expensive property. Every time you stay there
the
price goes up by $50!
```python
class Monopoly:
def __init__(self):
self.boardwalk_price = 500
@property
def boardwalk(self):
# In reality, this might represent a database call or time
# intensive task like calling a third-party API.
self.boardwalk_price += 50
return self.boardwalk_price
```
Now run it:
```python
>>> monopoly = Monopoly()
>>> monopoly.boardwalk
550
>>> monopoly.boardwalk
600
```
Let's convert the boardwalk property into a `cached_property`.
```python
from cached_property import cached_property
class Monopoly(object):
def __init__(self):
self.boardwalk_price = 500
@cached_property
def boardwalk(self):
# Again, this is a silly example. Don't worry about it, this is
# just an example for clarity.
self.boardwalk_price += 50
return self.boardwalk_price
```
Now when we run it the price stays at $550.
```python
>>> monopoly = Monopoly()
>>> monopoly.boardwalk
550
>>> monopoly.boardwalk
550
>>> monopoly.boardwalk
550
```
Why doesn't the value of `monopoly.boardwalk` change? Because it's a
**cached property**!
## Invalidating the Cache
Results of cached functions can be invalidated by outside forces. Let's
demonstrate how to force the cache to invalidate:
```python
>>> monopoly = Monopoly()
>>> monopoly.boardwalk
550
>>> monopoly.boardwalk
550
>>> # invalidate the cache
>>> del monopoly.__dict__['boardwalk']
>>> # request the boardwalk property again
>>> monopoly.boardwalk
600
>>> monopoly.boardwalk
600
```
|
Configuration Switches (platform-specific settings discarded)
PY312 OFF Build using Python 3.12
PY313 ON Build using Python 3.13
Package Dependencies by Type
Download groups
main |
mirror://PYPIWHL/11/0e/7d8225aab3bc1a0f5811f8e1b557aa034ac04bdf641925b30d3caf586b28 |
Distribution File Information
f617d70ab1100b7bcf6e42228f9ddcb78c676ffa167278d9f730d1c2fba69ccb 7428 python-src/cached_property-2.0.1-py3-none-any.whl
Ports that require python-cached-property:v13
No other ports depend on this one. |