__slots__ in Python: What It Is and Why You Need It

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What Is __slots__ and Why Do You Need It? A Complete Guide to Class Optimization in Python

In Python, classes are a cornerstone of object-oriented programming. However, when working with many objects, you might notice that your programs consume a significant amount of memory. This becomes especially critical when creating millions of instances of the same class.

That's where the special mechanism __slots__ comes in. It's not just a syntax feature—it's a powerful optimization tool that lets you control memory usage and speed up your programs.

Let's dive into what __slots__ is, how to use it, and when it's truly necessary.


What Is __slots__ in Python?

__slots__ is a special class attribute that restricts the list of allowed attributes for instances of that class.

By default, when you create objects in Python, their attributes are stored in a dictionary called __dict__. This is convenient but memory-inefficient, especially when creating many similar objects.

When you define __slots__, Python uses statically allocated structures to store attributes instead of a dictionary. This saves a lot of memory and speeds up attribute access.


📚 Simple Example Without Using __slots__:

python
class Person: def __init__(self, name, age): self.name = name self.age = age p = Person("Alice", 30) print(p.__dict__) # {'name': 'Alice', 'age': 30}

As you can see, all attributes are stored in __dict__.

Blogs

Book Recommendations