[Compiler-sig] __getattr__ inflexibility

Ludvig Svenonius ludvig.svenonius@excosoft.se
Fri, 31 Mar 2000 19:17:39 +0200


I was wondering about the __getattr__-built-in method. Currently it is
called only if the attribute could not be found in the instance dictionary.
Would it not be more flexible to -always- call it upon referencing an
attribute, thus allowing programmers to override the default behaviour of
simply returning the value matching the name (for example, the instance
could dispatch an event before returning the value, or update it from an
outside source). What I'm missing in Python is a feature to define derived
member fields that don't simply contain static values, but rather dynamic
ones (like method return values) but in every other respect behave like a
normal member (included in the dir() listing, but referenced without using
parentheses).

The reason I'm asking for this is that I am trying to create an API as
syntactically similar to the W3X XML DOM Core
(http://www.w3.org/TR/REC-DOM-Level-1/) as possible, but the actual objects
behind the interface are only stubs that reference a dynamic instance tree
inside a C++-application embedding the Python interpreter. Thus, I would
like to be able to reference DOM members such as Node.nodeValue using the
ordinary Python syntax (n.nodeValue) but the actual value cannot be
represented as a normal Python member, since it must be fetched from within
the C++ application (via a supplied extension). I could accomplish this by
defining methods to retrieve the value instead of members, but the DOM
standard defines that these values should be member fields, not methods, so
in order to achieve syntactical compliance with DOM, I have to somehow
intervene when the member is being referenced, and manually update its value
before it is returned. I tried using __getattr__ for this, but because of
the limitation that it is only called if the attribute is not found in the
instance dictionary, it didn't work. I could get the reference syntax to
work by just manually checking the attribute names in __getattr__, calling
the extension functions and returning the values, but then the dir()
function will not list the "simulated" members, because they are not
actually in the dictionary, and if I try to get around this by putting them
there, then __getattr__ won't be called.

Perhaps there is another way to do what I'm trying to accomplish, but if
not, would it not be a good idea to change the semantics of __getattr__ to
be more similar with __setattr_, so attribute referencing behaviour can be
overridden to allow things like composite and derived members?

==================================================================
  Ludvig Svenonius - Researcher
  Excosoft AB * Electrum 420 * Isafjordsgatan 32c
  SE-164 40 Kista * Sweden
  Phones: +46 8 633 29 58 * +46 70 789 16 85
  mailto:ludvig.svenonius@excosoft.se
==================================================================