Created
June 18, 2015 16:56
-
-
Save thmsmlr/8f17594fe0c642d64b89 to your computer and use it in GitHub Desktop.
Cached Property
This file contains 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
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