Skip to content

Instantly share code, notes, and snippets.

@z0u
Created September 2, 2016 14:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save z0u/9df24dda2b1fe0613a85e7349d5f7d62 to your computer and use it in GitHub Desktop.
Save z0u/9df24dda2b1fe0613a85e7349d5f7d62 to your computer and use it in GitHub Desktop.
Just like functools.lru_cache, but creates a new cache for each instance - which is more useful for methods.
def instance_method_lru_cache(*cache_args, **cache_kwargs):
'''
Just like functools.lru_cache, but a new cache is created for each instance
of the class that owns the method this is applied to.
'''
def cache_decorator(func):
@wraps(func)
def cache_factory(self, *args, **kwargs):
# Wrap the function in a cache by calling the decorator
instance_cache = lru_cache(*cache_args, **cache_kwargs)(func)
# Bind the decorated function to the instance to make it a method
instance_cache = instance_cache.__get__(self, self.__class__)
setattr(self, func.__name__, instance_cache)
# Call the instance cache now. Next time the method is called, the
# call will go directly to the instance cache and not via this
# decorator.
return instance_cache(*args, **kwargs)
return cache_factory
return cache_decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment