Skip to content

Instantly share code, notes, and snippets.

@surenkov
Created October 7, 2019 16:23
Show Gist options
  • Save surenkov/cb87609ffa743ebca9fa403ea2b0c805 to your computer and use it in GitHub Desktop.
Save surenkov/cb87609ffa743ebca9fa403ea2b0c805 to your computer and use it in GitHub Desktop.
Memoized Method descriptor
from functools import partial
class MemoizedMethod:
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
if obj is None:
return self.func
return partial(self, obj)
def __call__(self, obj, *args, **kw):
try:
cache = obj.__memo_cache
except AttributeError:
cache = obj.__memo_cache = {}
key = (self.func, args, frozenset(kw.items()))
try:
res = cache[key]
except KeyError:
res = cache[key] = self.func(obj, *args, **kw)
return res
memoized_method = MemoizedMethod
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment