Implementing deepcopy

Mr.Rech andrea.riciputi at
Thu Dec 8 05:03:26 CET 2005

Thanks for your answer. Since perfomances are not an issue in my case I
think I'd stay with copy.copy(). In this way I'm not required to know
in advance the object type, and I can implement a __deepcopy__ method
for my own classes as follows:

>>> def __deepcopy__(self, memo = {}):
            new = self.__class__.__new__(self.__class__)
            memo[id(self)] = new
            for key, val in self.__dict__.iteritems():
                     setattr(new, key, copy.deepcopy(val, memo))
                 except TypeError:
                     setattr(new, key, copy.copy(val))
            return new

The method is quite general (at least I hope so), and can be easily
inherited by all the subclasses without any major change. Is that
right? Am I missing something here? Any better way to implement this?

Thanks again,

More information about the Python-list mailing list