py2.1->py2.3.3 __getattr__ confusion
Peter Otten
__peter__ at web.de
Fri Jul 2 10:00:54 EDT 2004
Holger Joukl wrote:
> With introduction of the new style classes, something
> seems to have changed for __getattr__ hooks, even
> for classic classes:
Here is what I think it boils down to:
<joukl_getattr.py>
class A:
def __getattr__(self, name):
raise Exception
repr(A())
</joukl_getattr.py>
$ python2.1 joukl_getattr.py
$ python2.2 joukl_getattr.py
$ python2.3 joukl_getattr.py
Traceback (most recent call last):
File "joukl_getattr.py", line 20, in ?
repr(A())
File "joukl_getattr.py", line 18, in __getattr__
raise Exception
Exception
<joukl_getattr2.py>
class A:
def __getattr__(self, name):
print name
raise AttributeError
repr(A())
</joukl_getattr2.py>
$ python2.2 joukl_getattr2.py
__repr__
$ python2.3 joukl_getattr2.py
__repr__
That is, starting with Python 2.3 the repr() and str() functions no longer
mask exceptions other than AttributeError. Solution: make sure you raise an
AttributeError instead of the current KeyError for nonexistent attributes.
Peter
More information about the Python-list
mailing list