What is the Python __slots__ function?

Slots

Hello readers, this article will help you to understand what __slots__, their advantages, disadvantages, and usage.

What are __slots__?

It is used in class and object implementation programs.  __slots__ is a class variable that is usually assigned a sequence of strings that are variable names used by instances. The primary goal of using __slots__ is for faster access and memory saving in the program.

In Python when we implement a class, a class will have object instances and these object instances will have attributes, all these attributes are stored.

Python by default generates the __dict__ attribute to store values of all the instances in a particular class. Its implementation is very similar to the dict data type in Python.

__dict__ helps in dynamic variable creation, but in some cases, it is unable to catch errors. For example, if while writing the code, you by mistake misspell a variable name, instead of raising an AttributeError it will create a new variable. Problems like these are resolved in __slots__.

Also, the object instance using __slots__ doesn’t have a built-in dictionary this has two benefits first, the speed of accessing variables is faster, and second, much memory is saved. It does not create __dict__ for the class.

class Example_1_WithoutSlots():

    def __init__(self, roll_no, name):
        self.roll_no = roll_no
        self.name = name

x1 = Example_1_WithoutSlots('1', 'Adam')
print(x1.__dict__) 

OUTPUT:

{‘roll_no’: ‘1’, ‘name’: ‘Adam’}

class Example_2_WithSlots():
    __slots__ = ["roll_no", "name"]
   
    def __init__(self, roll_no, name):
        self.roll_no = roll_no
        self.name = name

x2 = Example_2_WithSlots('1', 'Adam')
print(x2.__dict__)

OUTPUT:

Screenshot 576
Output

Also, the object instance using __slots__ doesn’t have a built-in dictionary this makes accessing the instances much faster and saves memory also. To test we import timeit in python to check the speed of function in two classes. The first class implemented is without class and the second one with slots. We can clearly see the difference between both functions.

Implementing classes and functions

Classes
Classes

OUTPUT:

Screenshot 581
Output

Notice the difference between the time taken by both the functions. The first function takes 268ns per loop whereas the second function takes 237 ns per loop. In short programs like these, the difference doesn’t seem to be much but when developers develop a program on a larger scale, speed acts as a major factor.

Conclusion

__slots__ in Python is a very efficient way to increase the speed of the program and for faster access of attributes. It makes object-oriented programming easier.