Skip to content

Instantly share code, notes, and snippets.

@ktbarrett
Last active August 14, 2024 21:53
Show Gist options
  • Save ktbarrett/99daf49b001c0c98eb3058f5f2efdcd0 to your computer and use it in GitHub Desktop.
Save ktbarrett/99daf49b001c0c98eb3058f5f2efdcd0 to your computer and use it in GitHub Desktop.
For caching method calls on instances
from functools import update_wrapper, wraps
class cached_method:
def __init__(self, method):
self._method = method
update_wrapper(self, method)
def __get__(self, instance, objtype=None):
if instance is None:
return self
cache = {}
@wraps(self._method)
def lookup(*args, **kwargs):
key = (args, tuple(kwargs.items()))
try:
return cache[key]
except KeyError:
res = self._method(instance, *args, **kwargs)
cache[key] = res
return res
setattr(instance, self._method.__name__, lookup)
return lookup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment