def lazyprop(fn):
attr_name = '_lazy_' + fn.__name__
@property
def _lazyprop(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fn(self))
return getattr(self, attr_name)
return _lazyprop
class Test(object):
@lazyprop
def a(self):
print 'generating "a"'
return range(5)
t = Test()
b = t.a
%timeit b = t.a
generating "a" 100000 loops, best of 3: 2.45 µs per loop
class lazy_property(object):
'''
meant to be used for lazy evaluation of an object attribute.
property should represent non-mutable data, as it replaces itself.
'''
def __init__(self,fget):
self.fget = fget
self.func_name = fget.__name__
def __get__(self,obj,cls):
if obj is None:
return None
value = self.fget(obj)
setattr(obj,self.func_name,value)
return value
class Test(object):
@lazy_property
def a(self):
print 'generating "a"'
return range(5)
t = Test()
b = t.a
%timeit b = t.a
generating "a" 1000000 loops, best of 3: 322 ns per loop