Copy with __slots__

Antonio Cuni TOGLIMIcuni at programmazione.it
Thu Sep 19 15:01:50 EDT 2002


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...)

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)

Python 2.2 (#1, Feb 24 2002, 16:21:58)
[GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] on linux-i386
Type "help", "copyright", "credits" or "license" for more information.
>>> import copy, autocopy
>>> class foo(object):
...     __metaclass__ = autocopy.autocopy
...     __slots__ = ['x', 'y']
...
>>> f = foo()
>>> f.x = f.y = 41
>>> bar = copy.copy(f)
>>> print bar.x, bar.y
41 41

Anto
-- 
"Computer science is not about computers any more than astronomy
is about telescopes." -- EW Dijkstra



More information about the Python-list mailing list