Rewriting __getattr__

Jean-Michel Pichavant jeanmichel at sequans.com
Fri Jan 7 09:22:40 EST 2011


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


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /