Member-only story

In Python, __slots__

Elshad Karimov
2 min readApr 8, 2024
Photo by Clément Hélardot on Unsplash

In Python, __slots__ is a special attribute you can add to a class to restrict the attributes that instances of the class can have. Using __slots__ can lead to significant memory savings because it allows the Python interpreter to store instance attributes in a more compact way than a standard dictionary. This is particularly beneficial when creating many instances of a class.

Example: Using __slots__ in a Python Class

Let’s compare two classes, one using __slots__ and one without, to see the difference in their memory usage:

class RegularClass:
def __init__(self, name, identifier):
self.name = name
self.identifier = identifier

class SlotsClass:
__slots__ = ['name', 'identifier']

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

# Creating instances
reg_instance = RegularClass('test', 12345)
slots_instance = SlotsClass('test', 12345)

In this example, SlotsClass uses __slots__ to declare that instances will only have 'name' and 'identifier' attributes. This restriction eliminates the instance dictionary, a typical storage mechanism for an object's attributes, thus saving memory.

To observe the memory saving:

import sys

print(sys.getsizeof(reg_instance.__dict__)) # Memory…

--

--

Elshad Karimov
Elshad Karimov

Written by Elshad Karimov

Software Engineer, Udemy Instructor and Book Author, Founder at AppMillers

No responses yet