Created
December 23, 2013 16:06
-
-
Save estebistec/8099638 to your computer and use it in GitHub Desktop.
I have written the if hasattr dance for properties that load once WAY too many times...
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 memoized_property(fget): | |
""" | |
Return a property attribute for new-style classes that only calls | |
it's getter on the first property access. The result is stored | |
and on subsequent accesses is returned, preventing the need to call | |
the getter any more. | |
http://docs.python.org/2/library/functions.html#property | |
""" | |
attr_name = u'_{}'.format(fget.__name__) | |
@wraps(fget) | |
def fget_memoized(self): | |
if not hasattr(self, attr_name): | |
setattr(self, attr_name, fget(self)) | |
return getattr(self, attr_name) | |
return property(fget_memoized) | |
class A(object): | |
load_name_count = 0 | |
@memoized_property | |
def name(self): | |
"name's docstring" | |
self.load_name_count = self.load_name_count + 1 | |
return 'steven' | |
a = A() | |
assert a.load_name_count == 0 | |
print a.name | |
assert a.load_name_count == 1 | |
print a.name | |
assert a.load_name_count == 1 | |
assert a.name == a._name | |
assert A.name.__doc__ == "name's docstring" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment