Skip to content

Instantly share code, notes, and snippets.

@dutc
Created June 21, 2013 00:08
Show Gist options
  • Save dutc/5827890 to your computer and use it in GitHub Desktop.
Save dutc/5827890 to your computer and use it in GitHub Desktop.
How short & how complete can we write a memoising decorator? I think the below is more complete than most formulations (which don't cache independent of arg-binding.) I think it also cuts straight to the core of what memoisation means. Three obvious deficiencies: [1] What do we do about instance and class methods? These can be meaningfully memoi…
from sys import version_info
assert version_info.major == 3 and version_info.minor >= 3, \
'requires PEP 362; Python 3.3 or later; python.org/dev/peps/pep-0362/'
from inspect import signature
class memoise(dict):
def __init__(self, func):
self.func, self.signature = func, signature(func)
def __missing__(self, key):
args, kwargs = key
self[key] = self.func(*args, **dict(kwargs))
return self[key]
def __call__(self, *args, **kwargs):
key = self.signature.bind(*args, **kwargs)
return self[key.args, frozenset(key.kwargs.items())]
class Foo(object):
@memoise
def bar(x, y, z):
print('Foo.bar({}, {}, {})'.format(x, y, z))
return x + y + z
if __name__ == '__main__':
f = Foo()
assert f.foo(1,2,3) == f.bar(z=3,y=2,x=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment