From the course: Faster Python Code
Unlock the full course today
Join today to access over 24,700 courses taught by industry experts.
Using __slots__ - Python Tutorial
From the course: Faster Python Code
Using __slots__
- [Instructor] There are cases, when we create a lot of small objects. In most cases, this is fine, but it might be an issue, when the number of objects becomes very big. Python Objects store attributes in a dictionary called __dict__. Or dunder dict for short. Dictionaries in Python are optimized for access speed, and most of the time are 1/3 empty. Carrying a 1/3 empty dictionary per instance, can be a big overhead sometimes. For just these cases, Python offers us dunder slots, which remove the dunder dict. The downside of using dunder slots, is that you can't add new attributes to objects. Let's have a look at our code, in slots.py We have a class Point, which is the usual class. And we have the class SPoint, which, the only difference, is that we define, in line 17 dunder slots. In the main, we define two functions to allocate points. Once, in line 29, we allocate regular points, and in line 32, we allocate SPoints,…