Sitemap
Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Member-only story

Slots in Python

3 min readJun 24, 2025

--

Press enter or click to view image in full size
Art by Diwash Tamang (This amazing art can be yours for Only 1M$)

If you’ve used Python classes, you’ve probably written something like this:

class Player:
def __init__(self, name: str, score: int) -> None:
self.name = name
self.score = score

This works great. But under the hood, Python stores every attribute in a dictionary called __dict__. That’s flexible but a little memory-heavy, especially when you’re creating tons of instances.

But we can use a little trick by using slots when you want your classes to be lighter & a bit faster.

For non-members of the medium, click here to read the blog.

Where Python Stores Attributes (Normal Class)

In a non-slotted normal Python class, attributes go in a per-instance dictionary, like this.

class Player:
def __init__(self, name: str, score: int) -> None:
self.name = name
self.score = score

p = Player("Diwash", 75)
print(p.__dict__)
# {'name': 'Diwash', 'score': 75}

Using __slots__ to Save Memory

With __slots__, Python skips the __dict__ and stores attributes in a fixed structure. That saves memory & also speeds up attribute access by a tiny amount.

Turning normal classes into a slotted class is as easy as adding a line. Just add __slots__…

--

--

Diwash Tamang
Diwash Tamang

Written by Diwash Tamang

Geomatics Engineer | Python Developer | Lifelong Learner | Aspiring Blogger | Pursuit of Excellence

Dev Genius
Dev Genius

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development