Good question, slots can definitely help in some situations, but it’s not always worth using. By default, Python gives every object a dynamic dict, which allows you to add attributes at runtime, but that also uses more memory. When you define slots, you tell Python exactly which attributes an object can have, and it skips creating the dict, which can lead to significant memory savings, especially if you’re creating thousands or millions of instances. That said, there are tradeoffs. You lose the ability to add new attributes unless you explicitly include dict in the slots, and using slots can make inheritance a bit trickier, especially when combining it with other classes that also define slots. Also worth noting: if you’re using dataclasses, you’ll need to explicitly enable slots via @DataClass(slots=True) (available in Python 3.10+). In general, slots makes sense in performance-critical systems, like compilers, interpreters, or memory-heavy data processing pipelines, but for most everyday Python code, the benefits are usually too small to matter.
Many years ago I've made a small library to provide the __slots__ attribute to dataclasses: dataslots. It's stable, well-tested, and supports type checking. Additional features to python implementation:
Support for python 3.7 - 3.12 (python 3.10/3.11 added base support for slots).
Support for dynamic assignment for new variables (
__dict__in__slots__).Pickling frozen dataclasses (fixed in python 3.10).
Support for data descriptors and slots simultaneously.
If you are using older versions of python or need more from dataclasses give it a try.
Github: https://github.com/starhel/dataslots PyPI: https://pypi.org/project/dataslots/