Member-only story
Slots in Python
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 = scoreThis 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__…







