[Python-Dev] Computed-attributes

Donald Beaudry Donald Beaudry <donb@init.com>
Thu, 20 Jul 2000 12:11:38 -0400

Paul Prescod <paul@prescod.net> wrote,
> My first instinct is just to disallow this and figure it out after
> we have some more usage information/implementation resources. We
> could just say that all methods must be defined in the same class
> and if not. In other words, the methods "shadow each other" as a
> group.

One way of doing that, which I feel also makes things a bit more
obvious, is to allow only a single routine per attribute: __attr_XXX__.
Here's an example:

       def __attr_foo__(self, op, value=None):
           if op is 'get':
               return self.compute()
           elif op is 'set':

String interning makes the op tests quite fast.

> My second thought is to have the constructor for computed attributes
> objects look for a computed attribute higher in the tree and copy in
> the appropriate fields.

That sounds fragile and would create "book keeping" problems if
maintaining the current level of dynamic attribute magic is desired.

> Prohibiting it might be clearest for all concerned.

I agree that prohibiting it is the right idea.  The question is how.
Permitting only one routine per attribute lets the traditional
attribute lookup rules work and thus prevents head scratching when
trying to find the code that actually maintains an attribute.  The
cost is some additional burden on the writer of the __attr_XXX method
(and some magic to distinguish the del case).

Donald Beaudry                                     Ab Initio Software Corp.
                                                   201 Spring Street
donb@init.com                                      Lexington, MA 02421
                      ...Will hack for sushi...