[Tutor] class wrapper question (from Dive into Python) [copy.copy()]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed Mar 12 13:12:02 2003


On Wed, 12 Mar 2003, John Abbe wrote:

> I'm going through <http://www.diveintopython.org/>, and highly
> recommend it to all the other newbies out there. I'm halfway through
> chapter 3 before a serious question occurred to me. This, like not
> noticing the technology in computer animation movies, is a good thing.
>
> Okay...
>
>  From <http://www.diveintopython.org/fileinfo_specialmethods.html>,
> the old UserDict class:
>
> >     def clear(self): self.data.clear()          1
> >     def copy(self):                             2
> >         if self.__class__ is UserDict:          3
> >             return UserDict(self.data)
> >         import copy                             4
> >         return copy.copy(self)
> >     def keys(self): return self.data.keys()     5
> >     def items(self): return self.data.items()
> >     def values(self): return self.data.values()
>
> My question is, in copy, why bother with checking if it's a
> UserDict...why isn't it just like this?
>
>     def copy(self):
>        import copy
>        return copy.copy(self)



Hi John,


Interesting question!  One example with the default copy.copy() function
might help show why they're doing that:

###
>>> class Foo:
...     def __init__(self):
...         self.d = {}
...     def copy(self):
...         import copy
...         return copy.copy(self)
...
>>> x = Foo()
>>> x.d[42] = 'The answer!'
>>> y = x.copy()
>>> y.d
{42: 'The answer!'}
>>> x.d[13] = 'unlucky'
>>> y.d
{42: 'The answer!', 13: 'unlucky'}
###


The example above shows that the 'y' copy shares the same dictionary as
'x'.  copy.copy(), by default, does a shallow copy of an object.  This
explains why we use:

    return UserDict(self.data)

when we're trying to copy a UserDict -- we want to make a fresh new copy
of the internals, so that the copy isn't Siamese, so that it doesn't share
the internal structures with the original.


Hope this helps!  I sorta rushed this one; please feel free to ask
questions on any confusing points.