Copy with __slots__
Alex Martelli
aleax at aleax.it
Thu Sep 19 14:42:16 EDT 2002
Antonio Cuni wrote:
> Griebel, Peer wrote:
>
>> So my advice now is: Use slots! The program runs faster, uses less
>> memory. And explicitly coding a __copy__ function which copies each
>> attribute isn't a bad thing per se. It makes the things more explicit.
>
> (sorry for my bad english...)
English excellent, Python less so:-) (...just kidding...)
> we can make it easier by providing a metaclass that creates a __copy__
> method for us:
>
> class autocopy(type):
> def __new__(cls, name, bases, dic):
> def __copy__(self):
> res = self.__class__()
> for attr in dic['__slots__']:
> setattr(res, attr, getattr(self, attr))
> return res
>
> dic['__copy__'] = __copy__
> return type.__new__(cls, name, (object,), dic)
This doesn't deal with inherited __slots__. Easy to solve,
mind you -- autocopy.__new__ just needs to look for __slots__
in the bases, too, and accumulate them all into a sequence
on which the nested __copy__ function can loop. Some care
is needed, though (I can think of several possible anomalies).
Alex
More information about the Python-list
mailing list