Last active
August 14, 2024 21:53
-
-
Save ktbarrett/99daf49b001c0c98eb3058f5f2efdcd0 to your computer and use it in GitHub Desktop.
For caching method calls on instances
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
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