Rewriting __getattr__

kost BebiX kost-bebix at yandex.ua
Fri Jan 7 09:47:55 EST 2011


07.01.2011, 16:22, "Jean-Michel Pichavant" <jeanmichel at sequans.com>:
> kost BebiX wrote:
>
>>  You're absolutely right! Now try to do except Keyerror: raise AttributeError and it will also fail. But why?
>>
>>  07.01.2011, 15:45, "Jean-Michel Pichavant" <jeanmichel at sequans.com>;:
>>>  kost BebiX wrote:
>>>>   Hi everyone!
>>>>   I just saw a bug (?) in bson.dbref:DBRef.__getattr__
>>>>
>>>>   Here's they're code:
>>>>       def __getattr__(self, key):
>>>>           return self.__kwargs[key]
>>>>
>>>>   And when you do copy.deepcopy on that object it will raise you KeyError. So here's a small piece of code that reproduces the problem:
>>>  from http://docs.python.org/reference/datamodel.html
>>>
>>>  About __getattr__
>>>  "This method should return the (computed) attribute value or raise an
>>>  AttributeError
>>>  <http://docs.python.org/library/exceptions.html#exceptions.AttributeError>
>>>  exception."
>>>
>>>  The code you provided raises a KeyError thus methods such as 'getattr'
>>>  will fail as they expect an AttributeError exception.
>>>
>>>  JM
>>>
>>>  --
>>>  http://mail.python.org/mailman/listinfo/python-list
>
> please don't top post :)
>
> It fails because you simply did not returned any value (with your class
> A example).
>
> class A(object):
>     def __init__(self):
>         self.d = {}
>     def __getattr__(self, key):
>         try:
>             *return* self.d[key]
>         except KeyError:
>             raise AttributeError
>
> works fine with deepcopy
>
> JM
>
> --
> http://mail.python.org/mailman/listinfo/python-list

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>


-- 
jabber: k.bx at ya.ru



More information about the Python-list mailing list