folks, what's wrong with this?

Robert Kern robert.kern at gmail.com
Thu Apr 1 18:18:39 EDT 2010


On 2010-04-01 16:52 PM, Ani wrote:
> On Apr 1, 12:10 pm, Robert Kern<robert.k... at gmail.com>  wrote:
>> On 2010-04-01 13:56 PM, Ani wrote:
>>
>>
>>
>>> Hi All:
>>
>>> I am just a beginner in python. Can anyone please tell me what is
>>> wrong with this piece of code?
>>
>>> import copy
>>> class BaseDummyObject(object):
>>
>>>       def __init__(self):
>>>           pass
>>
>>>       def __getattr__(self, item):
>>>           try:
>>>               return self.__dict__.__getitem__(item)
>>>           except KeyError:
>>>               print "Attribute Error: attr %s of class %s non-existent!"
>>> %(item,
>>
>>> self.__class__.__name__)
>>
>> You need to raise an AttributeError here. Otherwise, it implicitly returns None
>> for all attributes not in the __dict__ and thus confusing the copy.deepcopy() code.
>>
>
> Thanks Robert. So I raised the exception and now everything looks
> good. So what's happening here? When a certain attribute is not
> available in the __dict__ and an exception is raised, who's catching
> it?

copy.deepcopy(), in this case, or one of the functions it calls. You can use 
traceback.print_stack() to see who is attempting to get the attribute. It is 
checking for certain methods on the object which control how the object gets 
seralized. copy.deepcopy() uses the same mechanism as pickle to serialize and 
reconstruct the object in memory.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list