Batu Lab NotesPractical developer guides

Use slots for many small dataclass instances

By Batu ยท English technical notes

Also published in our Blogger archive.

@dataclass(slots=True) is useful for a model with a fixed, small attribute set when an application creates many instances. It asks dataclass to generate __slots__, so a Point instance in this example has storage for x and y rather than a normal per-instance attribute dictionary. The list construction demonstrates an ordinary use case: several compact coordinate objects are created and their values are read normally.

The assertions check the calculated sums and show that this particular instance has no __dict__. They do not measure memory or prove a performance improvement; profile the real workload before making a memory or speed claim. Slots also restrict adding arbitrary new attributes, so they fit stable data shapes better than objects intended to be extended dynamically. If weak references are required, weakref_slot=True is a separate option and requires slots=True.

The slots argument was added in Python 3.10. It returns a new class during dataclass processing, and it cannot be used when the class already defines __slots__. For inherited dataclasses, use dataclasses.fields() rather than inspecting slots to discover fields.

AI assistance disclosure: this article was drafted with AI assistance and should be reviewed in the context of its target Python version.

Python dataclasses documentation documents slots=True, its version requirement, and its inheritance limitations.

from dataclasses import dataclass


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


points = [Point(index, index + 1) for index in range(3)]

assert [point.x + point.y for point in points] == [1, 3, 5]
assert not hasattr(points[0], "__dict__")

print(",".join(f"{point.x}:{point.y}" for point in points))
0:1,1:2,2:3