deepcopy problem
Stephen C Phillips
news at scphillips.co.uk
Wed Mar 12 05:38:33 EST 2003
On Tue, 11 Mar 2003 18:44:53 +0000, 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 get that too. Thanks for making it a simpler example - I hope a
solution to this will solve my problem too!
> I believe this to be a bug in the pickle module, one which is fixed in
> 2.3. 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.
Did you mean "g = copy.deepcopy(f, memo)" ?
If I do that then "g.foo is g" is true but that's only because "g is f"
is also true. From what I know about the copy module, the keys in the
memo are the id's of the objects being copied and the value of a key is
the copy of the object, so passing that memo to deepcopy tells it that the
copy of f is f and so g gets pointed at the original f.
So what we need is both "g is g.foo" and "g is not f" to be true.
I had a look at the SourceForge bug tracker for 2.2.2 and could not see a
bug listed for copy or pickle but I may be using it wrongly.
Stephen Phillips
More information about the Python-list
mailing list