deepcopy problem with new-style classes in Python 2.3a2

Steven Taschuk staschuk at telusplanet.net
Wed Mar 12 15:21:29 EST 2003


Quoth Stephen C Phillips:
  [...]
> 	With Python 2.3a2 (or Python 2.2.2) I get this:
> 
> >>> class Foo(object):
> ...     pass
> ... 
> >>> f = Foo()
> >>> f.foo = f
> >>> g = copy.deepcopy(f)
> >>> g is not f
> True
> >>> f is f.foo
> True
> >>> g is g.foo
> False
  [...]

I don't really know what I'm talking about, but I think the
problem is in copy._reconstruct, which in part reads:

    y = callable(*args)
    if state:
        if deep:
            state = deepcopy(state, memo)
        if hasattr(y, '__setstate__'):
            y.__setstate__(state)
        else:
            y.__dict__.update(state)
    return y

Here y is the copy being constructed, and callable, args, and
state are objects provided by object.__reduce__.  My notion is
that, since y is not added to the memo here, the deepcopy(state,
memo) call doesn't recognize f.foo as a reference to an object
already copied.

Inserting a line to put y in the memo as soon as it is built, thus:

    y = callable(*args)
    memo[id(x)] = y
    if state:

makes the symptom go away.  (This is similar to what the other
copying functions in the copy module do, so accommodate lists that
contain themselves and the like.)

Hopefully somebody who knows more about this can comment on this
proposal.

-- 
Steven Taschuk                             staschuk at telusplanet.net
"I may be wrong but I'm positive."  -- _Friday_, Robert A. Heinlein





More information about the Python-list mailing list