question: usage of __slots__

Alex Martelli aleaxit at yahoo.com
Sun Oct 12 16:36:56 EDT 2003


T. Kaufmann wrote:

> Can somebody give me some good examples of the usage of __slots__?

There aren't all that many, but here's one:

class point(object):
    __slots__ = ('x', 'y')
    def __init__(self, x, y):
        self.x = x
        self.y = y

thanks to the __slots__, each instance of point takes up little memory (in a 
32-bit machine, and assuming x and y are typically floats, about 40 bytes, 
I believe), saving the memory overhead of an instance dictionary (which
would more than double its size).  If you have millions of such instances in
memory at once, that matters!  There's a price to pay in terms of 
flexibility (can't simply annotate a given point by adding an attribute to 
it on the fly any more), but it may be considered worth paying when saving
lots and lots of memory calls for it.


Alex





More information about the Python-list mailing list