Slots for data classes

Slots for data classes

Have a data class (especially a frozen one) and want to make it more memory-efficient? You can add a __slots__ attribute but you’ll need to type all the field names out yourself.

from dataclasses import dataclass

@dataclass
class Point:
    __slots__ = ('x', 'y')
    x: float
    y: float

In Python 3.10 you can now use slots=True instead:

from dataclasses import dataclass

@dataclass(slots=True)
class Point:
    x: float
    y: float

This feature was actually included in the original dataclass implementation but removed before Python 3.7’s release (Guido suggested including it in a later Python version if users expressed interest and we did).

Creating a dataclass with __slots__ added manually won’t allow for default field values, which is why slots=True is so handy.

There’s a very smaller quirk with slots=True though: super calls break when slots=True is used because this causes a new class object to be created which breaks the magic of super.

But unless you’re using calling super().__setattr__ in the __post_init__ method of a frozen dataclass instead of calling object.__setattr__, this quirk likely won’t affect you.