A quick dive into Python’s “__slots__”
Nov 10, 2018 · 6 min reador 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
andself.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 calledw
: you couldn’t writew.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.
A quick dive into Python’s “__slots__” – Noteworthy – The Journal Blog
Pages: 1 2