Skip to content

Instantly share code, notes, and snippets.

@stefanor
Created March 7, 2013 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanor/5107102 to your computer and use it in GitHub Desktop.
Save stefanor/5107102 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
def memoize(f):
def wrapped(self):
attr_name = '_memoized_%s' % f.func_name
if not hasattr(self, attr_name):
setattr(self, attr_name, f(self))
return getattr(self, attr_name)
return wrapped
class Example(object):
@property
@memoize
def foo(self):
print "calculating foo"
return 12
@property
@memoize
def bar(self):
print "calculating bar"
return 42
if __name__ == '__main__':
e = Example()
print e.foo
print e.bar
print e.foo
print e.bar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment