__getattr__ and __setattr__ troubles

Niels Diepeveen niels at endea.demon.nl
Tue May 23 15:20:46 EDT 2000


Boudewijn Rempt schreef:

> From the documentation I understood that __getattr__ is only called when
> the ordinary normal mechanism fails. However, I see it being called even
> when my app needs things like __cmp__ and __repr__. though not for the
> fields I added myself after creating the object.

That's right. The normal mechanism for attribute lookup is to look in
__dict__. If that does not work __getattr__ is called. This goes for
methods as well as any other attributes.

...

> Traceback (innermost last):
>   File "./dbobj.py", line 66, in ?
>     main()
>   File "./dbobj.py", line 59, in main
>     if myrec==myrec2:
>   File "./dbobj.py", line 11, in __getattr__
>     return self.getFieldValue(name)
>   File "./dbobj.py", line 34, in getFieldValue
>     return self.__dict__[field]
> KeyError: __cmp__
> 
> I hope the solution is fairly simple and that I've only misread
> something ;-).

It is simple. __getattr__ is supposed to raise AttributeError, not
KeyError for non-existent attributes. If you change
   return self.__dict__[field]
to
   try:
       return self.__dict__[field]
   except KeyError:
       raise AttributeError(field)
you will get the default (identity based) comparison.

-- 
Niels Diepeveen
Endea automatisering




More information about the Python-list mailing list