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

John Abbe johnca@ourpla.net
Sun Mar 16 00:28:02 2003


At 10:11 AM -0800 2003-03-12, Danny Yoo wrote:
>On Wed, 12 Mar 2003, John Abbe wrote:
>  >  From <http://www.diveintopython.org/fileinfo_userdict.html>,
>  > the old UserDict class:
>  >
>  > >     def copy(self):                             2
>  > >         if self.__class__ is UserDict:          3
>>  >             return UserDict(self.data)
>>  >         import copy                             4
>  > >         return copy.copy(self)
>  >
>  > why bother checking if it's a UserDict...why isn't it just like this?
>  >
>>      def copy(self):
>>         import copy
>  >        return copy.copy(self)
>
>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.

Thanks, and now i have more questions...

Why not just use copy.deepcopy()? -- it avoids the Foo problem

When a subclass is created that doesn't have it's own copy method, 
why doesn't it fail the "if self.__class__ is UserDict" test and have 
the same problem?

>>>  class Eggs(UserDict):
...    pass
...
>>>  x=Eggs()
>>>  x.__class__
<class __main__.Eggs at 0x295ff0>
>>>  x[42]='answer'
>>>  y=x.copy()
>>>  y
{42: 'answer'}
>>>  x[13]='unlucky'
>>>  y
{42: 'answer'}

Life, (yes that is my regular sign-off... :)
John
-- 
  All you  /\/\ John Abbe           "If you don't like the news,
      need \  / CatHerder            go out and make some of your own."
      is... \/  http://ourpla.net/john/                --Wes Nisker