Using the LRU Cache decorator found here: http://code.activestate.com/recipes/578078-py26-and-py30-backport-of-python-33s-lru-cache/
from lru_cache import lr
How about this: a function decorator that wraps the method with lru_cache the first time it's called on each instance?
def instance_method_lru_cache(*cache_args, **cache_kwargs):
def cache_decorator(func):
@wraps(func)
def cache_factory(self, *args, **kwargs):
print('creating cache')
instance_cache = lru_cache(*cache_args, **cache_kwargs)(func)
instance_cache = instance_cache.__get__(self, self.__class__)
setattr(self, func.__name__, instance_cache)
return instance_cache(*args, **kwargs)
return cache_factory
return cache_decorator
Use it like this:
class Foo:
@instance_method_lru_cache()
def times_2(self, bar):
return bar * 2
foo1 = Foo()
foo2 = Foo()
print(foo1.times_2(2))
# creating cache
# 4
foo1.times_2(2)
# 4
print(foo2.times_2(2))
# creating cache
# 4
foo2.times_2(2)
# 4
Here's a gist on GitHub with some inline documentation.