Created
September 1, 2016 02:05
-
-
Save ar45/a08a05d34996d33e03391a81bfee3b1e to your computer and use it in GitHub Desktop.
python LRU cache instance method return value
This file contains hidden or 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
| from functools import lru_cache, wraps | |
| class cached_method: | |
| """Decorotor for class methods. | |
| Using pythons non data descriptor protocol, creates a new `functools.lru_cache` funcion wrapper | |
| on first access of a instances method to cache the methods return value. | |
| """ | |
| def __new__(cls, func=None, **lru_kwargs): | |
| if func is None: | |
| def decorator(func): | |
| return cls(func=func, **lru_kwargs) | |
| return decorator | |
| return super().__new__(cls) | |
| def __init__(self, func=None, **lru_kwargs): | |
| self.func = func | |
| self.name = func.__name__ | |
| self.lru_kwargs = lru_kwargs | |
| def __get__(self, instance, owner): | |
| if not instance: | |
| return self | |
| @wraps(self.func) | |
| def decorated_func(*args, **kwargs): | |
| return self.func(instance, *args, **kwargs) | |
| lru_cache_warpper = lru_cache(**self.lru_kwargs)(decorated_func) | |
| instance.__dict__[self.name] = lru_cache_warpper | |
| return lru_cache_warpper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment