Rewriting __getattr__

Jean-Michel Pichavant jeanmichel at sequans.com
Fri Jan 7 10:14:45 EST 2011


kost BebiX wrote:
> Sorry for top posting, didn't know about that) I'm quote new to posting to mailing lists.
>
> Well, actually the code you showed doesn't work)
>
>   
>>>> class A(object):
>>>>         
> ..     def __init__(self):
> ..         self.d = {}
> ..     def __getattr__(self, key):
> ..         try:
> ..             return self.d[key]
> ..         except KeyError:
> ..             raise AttributeError
>   
>>>> from copy import deepcopy
>>>> a = A()
>>>> deepcopy(a)
>>>>         
> Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
> Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
> 0: <__main__.A object at 0xda0250>
>
>
>   
It does work as I pasted it with python2.5.
recursion problems often occur when overriding __getattr__ or 
__getattribute__ *AND* accessing self attributes using self.attr form 
inside the method.

try to change

    return self.d[key]

into

    return object.__getattribute__(self, 'd')[key]

Just speculating though, I cannot test since I don't reproduce the problem.


JM



More information about the Python-list mailing list