Skip to content

Instantly share code, notes, and snippets.

@estebistec
Created December 23, 2013 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save estebistec/8099638 to your computer and use it in GitHub Desktop.
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...
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