Decorators for caching instance methods.
Project description
cachegrab
cachegrab is a Python package that provides decorators for caching instance methods.
Installation
pip install cachegrab
Main Features
deep_cached_property➔ Inspired by functools.cached_property, this decorator provides a deep copy of cached return values, ensuring they remain immutable after their initial access. The original return values are preserved in a dictionary namedself._deep_cache.cached_attribute➔ this decorator returns an internal attribute with the same name as the original, prefixed with an underscore.
Example Usage
Imports
from cachegrab import deep_cached_property, cached_attribute
from functools import cached_property
Decorate Instance Methods
Consider the example class Dog below:
toys➔ decorated withcached_propertybecause toys can be buried and are therefore mutable.is_good_boy➔ decorated withdeep_cached_propertybecause his good boy status is never in question.tricks➔ decorated withcached_attributeto prevent direct overwrites.
class Dog(object):
@cached_property
def toys(self):
return {'ball','bone'}
@deep_cached_property
def is_good_boy(self):
return True
@cached_attribute
def tricks(self):
return {'sit','shake'}
def bury_toys(self):
while self.toys:
self.toys.pop()
We will attempt to modify both cached properties:
dog = Dog()
dog.bury_toys()
dog.good_boy = False
Let's look at the results:
print('dog toys ➜', ', '.join(dog.toys) if dog.toys else '?')
print('good boy? ➜', dog.is_good_boy)
print('_deep_cache ➜', dog._deep_cache)
dog.tricks # access tricks property
print('_tricks ➜', dog._tricks)
dog toys ➜ ?
good boy? ➜ True
_deep_cache ➜ {'is_good_boy': True}
_tricks ➜ {'sit','shake'}
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
cachegrab-0.1.2.tar.gz
(3.2 kB
view hashes)
Built Distribution
Close
Hashes for cachegrab-0.1.2-py3-none-any.whl
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 | d7d0316c071bdf29ba3e80c250d3aa67d57c29bbdbdd7d3d0d3e2b815f9b4702 |
|
| MD5 | df0d756547ae8c8bafbed0077a75c8f0 |
|
| BLAKE2b-256 | 3c3b6c2ac26ac2d8a33eba782ac7b75e37f2ec6a19273f7c9173eae814e35c7a |