A quick dive into Python’s “__slots__” – Noteworthy – The Journal Blog

A quick dive into Python’s “__slots__”

Nov 10, 2018 · 6 min read

or my first Medium article, we’re going to go into a quick and easy way to speed up your Python code (and pass those pesky HackerRank tests where you’re just a bit short on time!), as well as some of the technical implementation details for the curious.

__slots__ is an attribute you can add to a Python class when defining it. You define slots with the possible attributes that an instance of an object can possess. Here’s how you use __slots__:

class WithSlots:
__slots__ = (‘x’, ‘y’)
def __init__(self, x, y):

self.x, self.y = x, y

For instances of this class, you can use self.x and self.y in the same ways as a normal class instance. However, one key difference between this and instancing from a normal class is that you cannot add or remove attributes from this class’ instances. Say the instance was called w: you couldn’t write w.z = 2 without causing an error.

The biggest higher-level reasons to use __slots__ are 1) faster attribute getting and setting due to data structure optimization and 2) reduced memory usage for class instances. Some reasons you wouldn’t want to use it is if your class has attributes that change during run-time (dynamic attributes) or if there’s a complicated object inheritance tree.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.