Python Class Slots

Python class slots are a feature that not many programmers know of. In a slotted class we explicitly define the fields that our class is allowed to have using the magic field name __slots__. This has some advantages:

  • Objects created from the class will take up slightly less memory
  • It’s faster to access class attributes
  • You can’t randomly add new attributes to objects of a slotted class

Here’s an example of how to define a slotted class:

>>> class Card:
...     __slots__ = 'rank', 'suite'
...     def __init__(self, rank, suite):
...             self.rank = rank
...             self.suite = suite
>>> qh = Card('queen', 'hearts')

To me, the biggest advantage is that you can’t randomly add new attributes to a slotted class. It can prevent costly mistakes! To demonstrate: a typo when assigning an attribute to a slotted class will throw an error instead of Python silently creating a new attribute.

For small classes without complex inheritance, using slots can be an advantage. Especially when you need to create many instances of such a class, the savings in memory and faster attribute access can make a difference.

Finally, just so you know, you can combine this technique with data classes as well!

About Erik van Baaren

Erik is the owner of Python Land and the author of many of the articles and tutorials on this website. He's been working as a professional software developer for 25 years, and he holds a Master of Science degree in computer science. His favorite language of choice: Python! Writing good articles takes time and effort. Did you like this tutorial? You can buy him a coffee to show your appreciation.

Notify of
Inline Feedbacks
View all comments

No, thanks!