Use of __slots__ in Python Class

__slots__

    Slots are predominantly used for avoiding dynamically created attributes. It is used to save memory spaces in objects. Instead of dynamically created objects at any time, there is a static structure that does not allow to after the initial creation. You would want to use __slots__ if you are going to instantiate a lot (hundreds, thousands) of objects of the same class. __slots__ only exists as a memory optimization tool. This reduces the overhead of the dict of every object that uses slots. Let us see an example with and without using slots;

Python class without __slots__

>>> class A(object):
...     pass
... 
>>> a = A()
>>> a.x = 66
>>> a.y = "dynamically created attribute"

The dictionary containing the attributes of “a” can be accessed like this:

>>> a.__dict__
{'y': 'dynamically created attribute', 'x': 66}

Python class with __slots__


    When we design a class, we can use slots to prevent the dynamic creation of attributes. To define slots, you have to define a list with the name __slots__. The list has to contain all the attributes, you want to use. We demonstrate this in the following class, in which the slots list contains only the name for an attribute “val”.

>>>class S(object):
...
...    __slots__ = ['val']
...
...    def __init__(self, v):
...        self.val = v
...
>>>x = S(42)
>>>print(x.val)
>>>x.new = "not possible"

Warning: Unfortunately there is a side effect of slots. Don’t prematurely optimize and use this everywhere! It’s not great for code maintenance, and it really only saves you when you have thousands of instances.

If you’re using __slots__ under PyPy, Read this Stackoverflow before you proceed.

References:

  1. https://docs.python.org/2/reference/datamodel.html#slots
  2. http://www.python-course.eu/python3_slots.php
  3. http://stackoverflow.com/questions/472000/python-slots