Computing class variable on demand?
fortepianissimo
fortepianissimo at gmail.com
Sat Feb 5 17:37:00 EST 2005
Thanks Steve - actually my question was simpler than that. I just
wanted to use Daniels' recipe of lazy initialization on objects with
__slots__:
class Lazy(object):
def __init__(self, calculate_function):
self._calculate = calculate_function
def __get__(self, obj, _=None):
if obj is None:
return self
value = self._calculate(obj)
setattr(obj, self._calculate.func_name, value)
return value
class SomeClass(object):
__slots__ = 'someprop'
@Lazy
def someprop(self):
print 'Actually calculating value'
return 13
o = SomeClass()
print o.someprop
print o.someprop
Running the code above will produce:
Actually calculating value
Traceback (most recent call last):
File "Lazy.py", line 26, in ?
print o.someprop
File "Lazy.py", line 11, in __get__
setattr(obj, self._calculate.func_name, value)
AttributeError: 'SomeClass' object attribute 'someprop' is read-only
Removing the __slots__ statement, everything would run normally.
Is there any workaround?
More information about the Python-list
mailing list