[Q] Deepcopy with Python 2.2 ?

Martin von Loewis loewis at informatik.hu-berlin.de
Fri Dec 28 13:37:31 EST 2001


setar at gmx.de (Oliver Hofmann) writes:

> I've had a few problems with copying objects lately when they 
> reference each other. My understanding is that deepcopy should 
> take care of that due to the memo - dictionary; this does not 
> seem to be the case. 
> 
> The following code works fine if Base does _not_ inherit 
> from object. If it does the result is:

I'd recommend to report this as a bug at sf.net/projects/python. What
happens is:

- you define a new type using new-style classes, i.e. none of the
  builtin deepcopiers applies. In particular, your instance's type
  is *not* <type 'instance'>
- your type does not implement __deepcopy__
- it does implement __reduce__ (as inherited from object)

Unfortunately, it appears that in the reduce case, the memo is not
taken into account. This is where I think the bug lies.

You can work around this problem by defining a __deepcopy__ method in
your Base class

    def __deepcopy__(self, memo):
        obj = object.__new__(self.__class__, None)
        memo[id(self)] = obj
        for k,v in self.__dict__.iteritems():
            obj.__dict__[k] = copy.deepcopy(v, memo)
        return obj

HTH,
Martin



More information about the Python-list mailing list