Obscure __getattr__ behavior

Alex Martelli aleax at aleax.it
Fri Feb 7 08:58:50 CET 2003


D. Herzberg wrote:
   ...
>     def __getattr__(self,name):
>         print "__getattr__(",name,")"
>         if name in self.__attributes__:
>             print "Lookup successful"
>             return self.__attributes__[name]
>         raise AttributeError, "%s not found" % (name)
   ...
> Sure, it is the raise statement but for some reason it doesn't
> raise anything. What makes the treatment of __repr__ special
> once we are in the __getattr__ function?
> 
> Any explanations?

You could schematize repr(x) as working as follows:

    try: return x.__repr__()
    except AttributeError:
         return '<%s instance at %x>' % (type(x), id(x))

[assuming type(x) returns x's class, as in the new object
model, for simplicity -- this issue is marginal to your
question anyway].  In other words, repr(x) EXPECTS x to
have no __repr__ method and thus to have to synthesize a
representation string if needed.  Your __getattr__ comes
into play in the x.__repr__ lookup, and *DOES* raise (just
as if you had no __getattr__, the lookup would alsor aise),
but repr() [which in your case is implicitly called by
the interactive interpreter] catches that exception and
compensates for it.


Alex





More information about the Python-list mailing list