Computing class variable on demand?

fortepianissimo fortepianissimo at gmail.com
Fri Feb 4 02:11:11 EST 2005


Thank you so much about this useful tip! I learned the new decorator
feature of 2.4 simply because of your post.

Unfortunately I don't have luxury right now to run Python 2.4 (for what
I'm doing anyways). You mentioned the way to do decorator in 2.3. Still
I have a question here. Here is Scott David Daniels's code for lazy
initialization:

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

The problem I run into using this for *instance* variables is: the
setattr() call won't work with a class with __slots__ defined - it
simply produces error that the attribute we want to modify is
read-only. Is there a workaround of this problem?

By the way this implementation is indeed better than the __getattr__
since in the latter I need to do a series of if... elif... else to
decide what to do with different attribute names. In the solution
above, I imagine the attribute names are hashed so it should have
better performance (the first time anyways).




More information about the Python-list mailing list