deepcopy questions

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Nov 28 01:46:35 CET 2012


On Tue, 27 Nov 2012 15:59:38 -0800, lars van gemerden wrote:

> Hi,
> 
> I get a very strange result when using deepcopy. The following code:
> 
>     def __deepcopy__(self, memo):
>         independent = self.independent()
>         if independent is self:
>             out = type(self)()
>             out.__dict__ = copy.deepcopy(self.__dict__, memo) 
>             print self.__dict__
>             print out.__dict__ #strange result
>             return out
>         else:
>             return copy.deepcopy(independent, memo).find(self.id).take()
> 
> prints different results for self.__dict__ and out.__dict__:

What makes you think that this is a strange result? What result are you 
expecting?

> {'_active_': False, 'init': {}, '_id_': 0, '_items_':
> [<flow.library.collector object at 0x03893910>], '_name_': 'main'}
> {'_active_': False, 'init': {}, '_id_': 0}
> 
> Two items are missing in the copy. Maybe i am missing something obvious,
> but i cannot figure out how this could happen.
> 
> Can anyone tell me how this is possible?

The most obvious guess is that the memo dict already contains _items_ and 
_names_, and so they get skipped.

Please ensure your sample code can be run. You should create the simplest 
example of stand-alone code that other people can run. See more 
information here:

http://sscce.org/


By the way, is it just me or is the documentation for deepcopy seriously 
lacking? http://docs.python.org/3/library/copy.html

There's no mention of the additional arguments memo and _nil, and while 
the docs say to pass the memo dictionary to __deepcopy__ it doesn't 
document any restrictions on this memo, how to initialise it, or under 
what circumstances you would pass anything but an empty dict.


-- 
Steven



More information about the Python-list mailing list