Skip to content

Instantly share code, notes, and snippets.

@ar45
Created September 1, 2016 02:05
Show Gist options
  • Save ar45/a08a05d34996d33e03391a81bfee3b1e to your computer and use it in GitHub Desktop.
Save ar45/a08a05d34996d33e03391a81bfee3b1e to your computer and use it in GitHub Desktop.
python LRU cache instance method return value
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