Skip to content

Instantly share code, notes, and snippets.

@thmsmlr
Created June 18, 2015 16:56
Show Gist options
  • Save thmsmlr/8f17594fe0c642d64b89 to your computer and use it in GitHub Desktop.
Save thmsmlr/8f17594fe0c642d64b89 to your computer and use it in GitHub Desktop.
Cached Property
def cached_property(func):
property_name = '_' + func.__name__
@functools.wraps(func)
def wrapped(self, *args, **kwargs):
private_property = getattr(self, property_name, None)
if kwargs.get('force', False) or private_property == None:
val = func(self, *args, **kwargs)
setattr(self, property_name, val)
return val
else:
return private_property
return property(wrapped)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment