DISCLAIMER: I'm the author of kids.cache.
You should check kids.cache
, it provides a @cache
decorator that works on python 2 and python 3. No dependencies, ~100 lines of code. It's very straightforward to use, for instance, with your code in mind, you could use it like this:
pip install kids.cache
Then
from kids.cache import cache
...
class MyClass(object):
...
@cache # <-- That's all you need to do
@property
def name(self):
return 1 + 1 # supposedly expensive calculation
Or you could put the @cache
decorator after the @property
(same result).
Using cache on a property is called lazy evaluation, kids.cache
can do much more (it works on function with any arguments, properties, any type of methods, and even classes...). For advanced users, kids.cache
supports cachetools
which provides fancy cache stores to python 2 and python 3 (LRU, LFU, TTL, RR cache).
IMPORTANT NOTE: the default cache store of kids.cache
is a standard dict, which is not recommended for long running program with ever different queries as it would lead to an ever growing caching store. For this usage you can plugin other cache stores using for instance (@cache(use=cachetools.LRUCache(maxsize=2))
to decorate your function/property/class/method...)