deepcopy problem with new-style classes in Python 2.3a2

Alex Martelli aleax at aleax.it
Thu Mar 13 13:53:14 EST 2003


Stephen C Phillips wrote:
   ...
>> ensure your new-style classes contain a __deepcopy__ that satisfies your
>> needs, such as:
>> 
>>     def __deepcopy__(self, memo):
>>         x = Foo.__new__(Foo)
>>         memo[id(self)] = x
>>         for n, v in self.__dict__.iteritems():
>>             setattr(x, n, copy.deepcopy(v, memo))
>>         return x
>> 
>> for new-style classes whose instances hold all of their state in
>> __dict__, and so on.
> 
> Thank you.  I thought it might be a bug, but I am not any where near
> expert enough to know.
> 
> My problem is not as simple as that described above, so I think that
> your work-around will not be sufficient.

Sure -- as I said, the specific example above is only for the simplest
case where all state is in self.__dict__.

> I have a class with several sub-classes (and sub-classes of those).
> Some of these classes may use __getstate__ and __setstate__ to remove
> some attributes from the copying process (and I would like the
> __getstate__ of the subclass to be in addition to the behaviour of its
> parent's __getstate__).  I think I can see how to begin modifying your
> work-around to cope with this (but cannot try code out from this
> computer!).
> 
> Would something like this be a good start?
> 
> def __deepcopy__(self, memo):
>      x = self.__class__.__new__(self.__class__)
>      memo[id(self)] = x
>      dict = {}

I suggest you avoid using builtin type names (such as dict) to
indicate specific instances of those types.  It does no harm in
this specific case, but it's a horrid habit that's sure to burn
you eventually.

>      for n, v in self.__getstate__.iteritems():
>          dict[n] = copy.deepcopy(v, memo)
>      x.__setstate__(dict)
>      return x

Yes, this looks good IF you know that self.__getstate__ does
return a dictionary that does all you want (but inheritance
could potentially make this 'if' quite tricky).


Alex





More information about the Python-list mailing list