Skip to content

Instantly share code, notes, and snippets.

@vbmendes
Created February 13, 2012 04:07
Show Gist options
  • Save vbmendes/1813557 to your computer and use it in GitHub Desktop.
Save vbmendes/1813557 to your computer and use it in GitHub Desktop.
cached_property decorator
from functools import wraps
def cached_property(fn):
@wraps(fn)
def wrapper(self):
cache_var = '_%s' % fn.__name__
if not hasattr(self, cache_var):
setattr(self, cache_var, fn(self))
return getattr(self, cache_var)
return property(wrapper)
from cached_property import cached_property
class UsageExample(object):
@cached_property
def slow_property(self):
# access_database()
o = UsageExample()
o.slow_property # hits database
o.slow_property # uses data cached in memory
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment