__slots__ magic

The special attribute __slots__ allows you to explicitly state which instance attributes you expect your object instances to have, with the expected results:

  1. faster attribute access.

  2. space savings in memory.

The space savings is from

  1. Storing value references in slots instead of __dict__.

  2. Denying __dict__ and __weakref__ creation if parent classes deny them and you declare __slots__.

Every class can have instance attributes. By default Python uses a dict to store an object’s instance attributes. This allows setting arbitrary new attributes at runtime.

For small classes with known attributes it might be a bottleneck. The dict wastes a lot of RAM. Python can’t just allocate a static amount of memory at object creation to store all the attributes. Therefore it sucks a lot of RAM if you create a lot of objects (I am talking in thousands and millions). Still there is a way to circumvent this issue. It involves the usage of __slots__ to tell Python not to use a dict, and only allocate space for a fixed set of attributes.

Example:

Without __slots__:

class MyClass(object):
    def __init__(self, name, identifier):
        self.name = name
        self.identifier = identifier
        self.set_up()
    # ...

With __slots__:

class MyClass(object):
    __slots__ = ['name', 'identifier']
    def __init__(self, name, identifier):
        self.name = name
        self.identifier = identifier
        self.set_up()
    # ...

Using __slots__ will reduce the burden on your RAM.

Sidenote: you might want to try PyPy: it does all of these optimizations by default.

Last updated