Skip to content

Instantly share code, notes, and snippets.

@pavelpy
Last active April 11, 2024 08:57
Show Gist options
  • Save pavelpy/69f8cdad94aaf59abcf879bda66bfd1a to your computer and use it in GitHub Desktop.
Save pavelpy/69f8cdad94aaf59abcf879bda66bfd1a to your computer and use it in GitHub Desktop.
python functools lru_cache with class methods
# origin: https://stackoverflow.com/questions/33672412/python-functools-lru-cache-with-class-methods-release-object
import functools
import weakref
def memoized_method(*lru_args, **lru_kwargs):
def decorator(func):
@functools.wraps(func)
def wrapped_func(self, *args, **kwargs):
# We're storing the wrapped method inside the instance. If we had
# a strong reference to self the instance would never die.
self_weak = weakref.ref(self)
@functools.wraps(func)
@functools.lru_cache(*lru_args, **lru_kwargs)
def cached_method(*args, **kwargs):
return func(self_weak(), *args, **kwargs)
setattr(self, func.__name__, cached_method)
return cached_method(*args, **kwargs)
return wrapped_func
return decorator
@Susensio
Copy link

Thank you for your code. I made some modifications based on this.
https://gist.github.com/Susensio/61841aa8186da1a06f54ba1e0b1a9b64
Added type hints and allow for decorator to be called without parenthesis.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment