Created
September 2, 2016 14:39
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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