Should You Use Slots? How Slots Affect Your Class, and When and How to Use Them | by Mike Huls | Aug, 2023

One line of code for a 20% performance increase?

(image by Sébastien Goldberg on Unsplash)

Slots are a mechanism that allow you to declare class attributes and restrict the creation of other attributes. You establish which attributes your class has, preventing developers from adding new attributes dynamically. This generally leads to a 20% speed increase.

Slots are especially beneficial in programs where you have a large number of class instances with a known set of attributes. Think of a video games or physics simulations; in these situations you track a large number of entities over time.

You can add slots to your class adding a single line of code but is this always a good idea? In this article we’ll look a why and how using slots make your classes that much faster and when to use them. The overall goal is to better understand how Python’s class internals work. Let’s code!

You can improve a class’ memory usage and performance by making it use slots. A class with slots takes up less memory and executes faster.

How to make my class use slots?

Telling Python to make a class use slots is very simple. You just add a special attribute called __slots__ that specifies the names of all other attributes:

class Person:

__slots__ = ['first_name', 'last_name', 'age'] # <-- this adds slots

def __init__(self, first_name:str, last_name:str, age:int):
self.first_name = first_name
self.last_name = last_name
self.age = age

In the class above we see that Person has three attributes: first_name, last_name, and age. We can tell Python that we want the Person class to use slots by adding the __slots__ attribute. This attribute has to specify the names of all other attributes.

Source link

Leave a Comment