[Tutor] copying

Daniel Yoo dyoo@hkn.EECS.Berkeley.EDU
Mon, 21 Aug 2000 00:32:46 -0700 (PDT)

> I've run across a bit of a problem and I'm hoping that either it's
> all my fault because I've done something silly  or someone can suggest a
> solution. Over the weekend I was very excited to find the generic shallow
> and deep copying operations because they were exactly what I needed at
> that point in my coding. I got the functions working on some basic
> examples but when I sat down to try it out on the real thing I've found
> that since I'm using kjSets as one of the data types in my list deepcopy
> doesn't work. Sample code from an investigation session is below.
> My question: Is there anyway of getting around this? I really need
> deepcopy to work regardless of what you give it since I'm getting it to
> copy the __dict__ of an object. Am I likely to run into this problem again
> with other objects? 

Ok, I found a workaround, and it's not quite bad.  If you look at the
source for the copy module, Lib/copy.py, you'll actually see a LOT of
workarounds for the base types.  What I've done is write up a small
module, called "kjcopy.py", that imitates them.  Load it up before you do
any copying, and things should work ok, at least of kjSets:

### kjcopy.py
import kjbuckets
import copy

def _copy_kjSet(x):
    return kjbuckets.kjSet(x)

copy._copy_dispatch[type(kjbuckets.kjSet())] = _copy_kjSet

Here's it in action:

>>> from kjbuckets import *
>>> from copy import *
>>> import kjcopy
>>> s = kjSet([1, 2, 3, 4, 5])
>>> s2 = copy(s)
>>> s.add(42)
>>> s
kjSet([1, 2, 3, 4, 5, 42])
>>> s2
kjSet([1, 2, 3, 4, 5])

To whoever wrote copy.copy(), thank you for the readable code! *grin* I
haven't gotten around to patching up copy() for the other kjTypes, but it
should look very similar.