Mastering Python Class Slots: Optimize Memory & Speed
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!
Python
- Mastering Python Operators: A Comprehensive Guide
- Python List Operations: Creation, Access, Modification, and Advanced Techniques
- Mastering Python Custom Exceptions: A Practical Guide
- Mastering Python Object‑Oriented Programming: Classes, Inheritance, Encapsulation & Polymorphism
- Mastering Python Objects & Classes: A Practical Guide
- Mastering Python Inheritance: Concepts, Syntax, and Practical Examples
- Master Python Multiple Inheritance, Multilevel Inheritance, and Method Resolution Order (MRO)
- Understanding type() and isinstance() in Python: Practical Examples
- Python Data Classes: Streamline Data Management with Modern Syntax
- Master Python's Object-Oriented Programming: A Comprehensive Guide