Re: Semi-newbie, rolling my own __deepcopy__



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

.



Relevant Pages

  • Re: Semi-newbie, rolling my own __deepcopy__
    ... But I now have succeeded in making deepcopy work for a simple class ... print "clone, should be deepcopy of foo:", clone.show ... from array import array ... bundled into a dictionary with numerics first, ...
    (comp.lang.python)
  • Re: Java Reflection question
    ... stack frames from the stack trace. ... is permitted to return a zero-length array from this method. ... Try to get the first element of the array without checking its length ...
    (comp.lang.java.programmer)
  • Re: Can we copy stack trace of Excepion in a string?
    ... The first is to use the getStackTracemethod, which returns an array ... just log the parts of the stack trace you are interested in. ... The second way is to create a StringWriter class to capture the output ... from the Exception using the printStackTracemethod. ...
    (comp.lang.java)
  • Casting DataGridItem - Corrected Posting
    ... array of Row ID's. ... get 'Specified cast is not valid error 'on the line that is casting the ... // Add changed record ID's to ChangedRecordList for SaveRecord loop ... Please review the stack trace for more information ...
    (microsoft.public.dotnet.framework.aspnet.datagridcontrol)
  • Re: encoding hell - any chance of salvation ?
    ... and results in the error"TypeError: array item must be unicode ... character" is raised (full stack trace at bottom). ... Can anyone make a suggestion as to the best way to allow the array ... array item must be unicode character ...
    (comp.lang.python)