Copying objects style questions

Bengt Richter bokr at oz.net
Wed Aug 6 10:18:32 EDT 2003


On Wed, 06 Aug 2003 10:23:16 GMT, Alex Martelli <aleax at aleax.it> wrote:

>Bob Halley wrote:
>   ...
>> I can't use copy.copy()'s default behavior, because it is too shallow.
>> I don't want to use copy.deepcopy() because it's too deep.  I
>
>So far, so perfectly clear.
>
>> contemplated __copy__, __initargs__, __getstate__, and __setstate__,
>> but they didn't seem to fit the bill, or seemed more complicated than
>> the solution I ended up with (see below).
>
>I don't understand this.  What's wrong with, e.g.:
>
>def __copy__(self):
>    class EmptyClass: pass
>    obj = EmptyClass()
>    obj.__class__ = self.__class__
>    obj.__dict__.update(self.__dict__)
>    obj.items = list(self.items)
>    return obj
>
>???  It seems simpler and more automatic than your 'copy protocol';
>subclasses don't need to do anything special unless they need to
>"deepen" the copy of some of their attributes.  Btw, if you're
>using new-style classes, you'll want to use object instead of
>EmptyClass, or start with obj = self.__class__.new(self.__class__)

<nits>
I don't think you meant object() as a direct substitute for EmptyClass() above, right?
And you meant to put tails on that "new," presumably.
</nits>

>as you're doing in your protocol, of course -- but the key idea
>is "bulk copy all that's in self's __dict__, then special-case
>only what little needs to be specialcased".  And doing it in a
>method called __copy__ means any user of your class needs not
>learn about a new copy protocol but rather just uses copy.copy.
>
>It may be that I'm not correctly understanding your issues, of
>course, but I hope these suggestions can help.
>
>
>Alex
>

Regards,
Bengt Richter




More information about the Python-list mailing list