Semi-newbie, rolling my own __deepcopy__

Michael Spencer mahs at telcopartners.com
Thu Apr 21 22:21:05 EDT 2005


Michael Spencer wrote:
> http://www.python.org/doc/2.3.3/lib/module-copy.html
> deepcopy:
> ...
> This version does not copy types like module, class, function, method, 
> stack trace, stack frame, file, socket, window, *array*, or any similar 
> types.
> ...
> 
On reflection, I realize that this says that the array type is not 
deep-copyable, not array instances.  Still, it does appear that array instances 
don't play nicely with deepcopy

It appears that if you want to deepcopy an object that may contain arrays, 
you're going to have to 'roll your own' deep copier.  Something like this would 
do it:

class Test1(object):

     def __init__(self, **items):
         self.items = items

     def __deepcopy__(self, memo={}):
         mycls = self.__class__
         newTestObj = mycls.__new__(mycls)
         memo[id(self)] = newTestObj

         # We need a deep copy of a dictionary, that may contain
         # items that cannot be deep copied.  The following code
         # emulates copy._deepcopy_dict, so it should act the same
         # way as deepcopy does.

         x = self.items
         y = {}
         memo[id(x)] = y
         for key, value in x.iteritems():
             try:
                 newkey = deepcopy(key, memo)
             except TypeError:
                 newkey = copy(key)
             try:
                 newvalue = deepcopy(value, memo)
             except TypeError:
                 newvalue = copy(value)
             y[newkey] = newvalue

         newTestObj.__init__(**y)
         return newTestObj

     def __repr__(self):
         return '%s object at %s: %s' % (self.__class__.__name__
                                     , hex(id(self)), self.items)

  >>> t = Test1(a=array("d",[1,2,3]))
  >>> t
  Test1 object at 0x196c7f0: {'a': array('d', [1.0, 2.0, 3.0])}
  >>> t1 = deepcopy(t)
  >>> t1
  Test1 object at 0x1b36b50: {'a': array('d', [1.0, 2.0, 3.0])}
  >>>

BTW: are you sure you really need to copy those arrays?

Michael




More information about the Python-list mailing list