Created
February 13, 2012 04:07
-
-
Save vbmendes/1813557 to your computer and use it in GitHub Desktop.
cached_property decorator
This file contains hidden or 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
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) |
This file contains hidden or 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
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