Created
October 7, 2019 16:23
-
-
Save surenkov/cb87609ffa743ebca9fa403ea2b0c805 to your computer and use it in GitHub Desktop.
Memoized Method descriptor
This file contains hidden or 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 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