Understanding __slot__ magic method

Posted by Afsal on 09-Sep-2022

Hi Pythonistas!

Today we will learn about the __slot__ magic method. We can make the class more efficient and make class attributes fixed, That is we cannot edit attributes dynamically. Let’s learn with an example

code

class Student:

    def __init__(self, name, age, address):
        self.name = name
        self.age = age
        self.address = address

a = Student("Test", 12, "abcd")
print(a.name)
print(a.age)
print(a.address)
a.abc = "test"
print(a.abc)

Output

Test
12
abcd
test

Here in this example we can add attribute abc dynamically.

Code

class StudentSlotted:
    __slots__ = ["name", "age", "address"]

    def __init__(self, name, age, address):
        self.name = name
        self.age = age
        self.address = address

b = StudentSlotted("Test", 12, "abcd")
print(b.name)
print(b.age)
print(b.address)

b.abc = "test"
print(b.abc)

Output

Test
12
abcd

Traceback (most recent call last):
  File "main.py", line 33, in <module>
    b.abc = "test"
AttributeError: StudentSlotted object has no attribute 'abc'

Here in this example we cannot modify the attribute dynamically.

Why

Normally in the class the attributes are stored in dict. We can access the dict by __dict__

code

print(a.__dict__)

Output

{'name': 'Test', 'age': 12, 'address': 'abcd', 'abc': 'test'}

But if we use __slots__ there is no dictionary. Attributes are stored directly as fields in the object. This makes the class attribute fixed and less in size

Let us check the size of the object using a module class pympler

Code

from pympler import asizeof
print("Size of student object is: ", asizeof.asizeof(a))
print("Size of student slotted object is: ", asizeof.asizeof(b))

Output

Size of student object is:  464
Size of student slotted object is:  200


Hope you have learned something from this post. Please share your thought at afsal@parseltongue.co.in.