deepcopy problem

Alex Martelli aleax at aleax.it
Fri Mar 14 12:45:55 CET 2003


Jp Calderone wrote:
   ...
>   I think the essense of this problem can be distilled thusly:
> 
>   import copy
>   class Foo(object): pass
>   f = Foo()
>   f.foo = f
>   g = copy.deepcopy(f)
> 
>   "f.foo is f" is True, while "g.foo is g" is False.

Yes.

>   I believe this to be a bug in the pickle module, one which is fixed in
> 2.3.  

Perhaps related, but this specific issue with the copy module is
not yet fixed in 2.3 -- here's an example with 2.3 built right
out of CVS:


>>> from copy import deepcopy as dc
>>> class Foo(object): pass
...
>>> f=Foo()
>>> f.foo=f
>>> g=dc(f)
>>> f.foo is f
True
>>> g.foo is g
False
>>>

> There seems to be a work-around in 2.2, though I haven't explored
> its behavior very thoroughly:
> 
>   import copy
>   class Foo(object): pass
>   f = Foo()
>   f.foo = f
>   memo = {id(f): f}
>   g = copy.deepcopy(f)
> 
>   Now, "g.foo is g" is True.

Maybe you meant to pass memo as the second argument of deepcopy --
without that, I can't see how this could possibly work.  WITH it,
it does indeed fix this specific symptom (in 2.3 from CVS):

>>> memo = {id(f): f}
>>> g = dc(f, memo)
>>> g.foo is g
True
>>>


Alex





More information about the Python-list mailing list