deepcopy problem

Jp Calderone exarkun at intarweb.us
Tue Mar 11 19:44:53 CET 2003


On Tue, Mar 11, 2003 at 10:03:29AM +0000, Stephen C Phillips wrote:
> Hi,
> 	I have refined my problem and have a smaller example now.  I have a
> class called 'Node' which is a new-style class and has a name and a
> 'neighbour' which is another Node object.  I make a node 'n' and a node
> 'm' and point n at m AND m at n, so n.neighbour.neighbour is n.  I then do
> a deepcopy of n into x. This of course makes a copy of m too.  I then
> print x (and it looks just like n) but the dictionary of
> x.neighbour.neighbour is empty and x.neighbour.neighbour is not x.
> 	If I make Node an old-style class (by just using "class Node:") then it
> all works fine and x.neighbour.neighbour is x.  I am using Python 2.2.2.
> Can anyone explain what difference between old and new-style classes causes this
> please?
> 	Once again, the __getstate__() and __setstate__() methods are in there
> just to help diagnose the problem and the code works the same without
> them.
> 
> Thanks.
> 

  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.

  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.
 

  Hope this helps,

  Jp

-- 
"There is no reason for any individual to have a computer in their
home."
                -- Ken Olson, President of DEC, World Future Society
                   Convention, 1977
-- 
 up 8 days, 9:59, 8 users, load average: 0.00, 0.05, 0.07





More information about the Python-list mailing list