copy a class

Steven Taschuk staschuk at telusplanet.net
Fri Jun 13 01:33:09 CEST 2003


Quoth Turhan Ozen:
  [...]
> TypeError: can't pickle function objects
  [...]
>  I am making a copy of a class instance so that the original instance is 
> not changed when I use it in some operations. But one attribute of this 
> class is a reference to a function. Is this a problem? Could you please 
> recommend me a solution?

First, here's the difference between copy and deepcopy:

    >>> import copy
    >>> class Foo(object):
    ...     pass
    ... 
    >>> x = Foo()
    >>> x.a = 3
    >>> x.b = [1, 2]  
    >>> y = copy.copy(x)       # With shallow copy,
    >>> x is y                 # x and y are different objects,
    0
    >>> y.a = 'not three'      # so attribute assignment to one does
    >>> x.a                    # does not affect the other, like you'd expect.
    3
    >>> x.b is y.b             # But the *referred to* objects are not copied
    1
    >>> y.b.append(3)          # so if they're mutable
    >>> x.b                    # x and y can share data.
    [1, 2, 3]
    >>> z = copy.deepcopy(x)   # Whereas with deep copy,
    >>> x.b is z.b             # the referred to objects are also copied
    0
    >>> z.b.append(4)          # so the copy is much more independent
    >>> x.b                    # of the original.
    [1, 2, 3]

So, for example, if you have an instance attribute which refers to
a function, copy.deepcopy will try to copy that function too,
which it can't do.  Hence the exception you've seen.

Using copy.copy would avoid *that* problem, but look carefully at
the above example interactive session and make sure you understand
what it does differently, and whether that would work for you.
Try similar experiments with your own classes.

If neither shallow nor deep copy is what you want, you can
implement your own copying logic using __getstate__ and
__setstate__, for example.  More on that if you ask.

-- 
Steven Taschuk                               staschuk at telusplanet.net
"What I find most baffling about that song is that it was not a hit."
                                          -- Tony Dylan Davis (CKUA)





More information about the Python-list mailing list