Rewriting __getattr__
kost BebiX
k.bx at ya.ru
Fri Jan 7 10:18:43 EST 2011
07.01.2011, 17:14, "Jean-Michel Pichavant" <jeanmichel at sequans.com>:
> 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
Yeap, that works. So, is it a python 2.6 bug? Because documentation says that __getattr__ is called only after property was not found (and __getattr__ was actually invented in a way that you can use self inside it).
--
jabber: k.bx at ya.ru
More information about the Python-list
mailing list