Copying objects style questions

Alex Martelli aleax at aleax.it
Wed Aug 6 11:36:07 EDT 2003


Bengt Richter wrote:
   ...
>>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()

Right -- you couldn't assign __class__ on an object() result, for example.

> above, right? And you meant to put tails on that "new," presumably.
> </nits>

Right again.  So, for completeness, with a new-style class you could
do, e.g. (probably optimal or close to it):

    def __copy__(self):
        obj = self.__class__.__new__(self.__class__)
        obj.__dict__.update(self.__dict__)
        obj.items = list(self.items)
        return obj

Sorry for the sloppy expression in those hurriedly-written two lines;-).

To forestall further misunderstandings -- this would not work for
objects with __slots__ (no __dict__) or inheriting from classes with
__slots__ (wouldn't copy attributes not in __dict__) -- there is
always more work needed for such cases.  But if one uses __slots__
one *deserves* to have to work a bit harder as a result;-).


Alex





More information about the Python-list mailing list