Python Dataclasses Advanced: frozen, slots, and Inheritance
Beyond basic data classes, there are features for immutability, memory efficiency, and inheritance. Here is when I use each one. The basic @dataclass decorator generates __init__ , __repr__ , and __eq__ . That covers most use cases. But the decorator accepts parameters that change its behavior significantly: frozen for immutability, slots for memory efficiency, and order for comparison methods. Understanding these options changed how I use dataclasses. Frozen Dataclasses for Immutability A frozen dataclass cannot be modified after creation. Attempting to set an attribute raises FrozenInstanceError . This makes instances hashable, which regular dataclasses are not. from dataclasses import dataclass @dataclass(frozen=True) class Point: x: float y: float p = Point(1.0, 2.0) # p.x = 3.0 # raises FrozenInstanceError # Frozen instances are hashable points = {Point(1, 2), Point(3, 4), Point(1, 2)} # {Point(x=1.0, y=2.0), Point(x=3.0, y=4.0)} I use frozen dataclasses for configuration objects, value objects, and any data that should not change after creation. Immutability prevents a class of bugs where an object is modified in one place and breaks code that holds a reference to it. Slots for Memory Efficiency By default, Python instances store attributes in a __dict__…