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!

Get certified with our courses

Learn Python properly through small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

Leave a Comment

Python Newsletter

Before you leave, you may want to sign up for my newsletter.

Tips & Tricks
News
Course discounts

Googler exit intent popup

No spam & you can unsubscribe at any time.