Section 12.45

Dataclass

Definition

A dataclass is a Python §12.23 class whose routine methods are written automatically from a list of declared fields. Writing @dataclass above a class turns each attribute declared with a type, such as port: int, into a field. It then adds a constructor that stores one argument per field, a printable form, and an equality test that compares the fields in order. The option frozen=True makes assigning to a field after construction raise an error. Neither the declared types nor the freezing reach into the objects that the fields refer to.

The idea

A record class written by hand repeats every field name in the constructor, in the method that prints the object and in the method that compares two objects. Add a field, forget it in the comparison method, and two records that differ only in that field compare equal, with no error message anywhere. A dataclass lists the fields once and generates the methods from that list, so the methods cannot drift apart from the fields.

Python variables and fields hold references: pointers to objects that live elsewhere in memory. Rebinding a field, r.items = other, makes it point to a different object. Mutating an object, r.items.append(2), changes the object that the field already points to and leaves the field untouched. frozen=True forbids rebinding. It cannot forbid mutation, which happens inside the list object, and the list knows nothing about the record that points to it. A frozen record is like a sealed card that lists locker numbers: nobody can rewrite the card, but anyone can open locker 12 and change what is inside. The picture stops at the seal itself, which a determined program can break, as the limits below show.

How it works

A decorator is a function that Python applies to a class, or to a function, right after defining it; the line @dataclass requests that. The dataclass decorator, from the standard module dataclasses (Python 3.7 and later), works in four steps.

  1. Collect the fields. Every class attribute with a type annotation §12.46, the : int part, becomes a field, in the order written. Fields inherited from a base class that is itself a dataclass come first. A value after the annotation, as in port: int = 80, is the field’s default.

  2. Generate methods. By default the decorator writes three methods. __init__, the constructor, takes one argument per field and stores it. __repr__ returns text such as Config(name='radio', port=80). __eq__ treats two instances as equal when they are of exactly the same class and their fields are equal in order.

  3. Freeze, if asked. With frozen=True, the decorator also writes __setattr__ and __delattr__, the methods Python calls for obj.f = v and del obj.f. Both raise FrozenInstanceError, a kind of AttributeError. The generated constructor stores the fields through object.__setattr__, which skips the block.

  4. Decide hashing. A hash is a number that Python’s dictionaries and sets compute from an object to find where to store it; equal objects must have equal hashes. With the default eq=True and with frozen=True, the decorator writes __hash__ from the field values. With eq=True and frozen=False, it sets __hash__ to None, so instances cannot be dictionary keys: a hash computed from fields that may later change would go stale.

A default value is created once, when the class is defined, so a mutable default such as items: list = [] would be one list shared by every instance. The decorator refuses such a default with ValueError; field(default_factory=list) creates a new list for each instance. A method named __post_init__, if the class defines one, runs at the end of the generated constructor and is the place for checks and conversions.

Worked example

After from dataclasses import dataclass, define a frozen record with a name and a list of ports:

@dataclass(frozen=True)
class Config:
name: str
ports: list

Run these statements in order.

  1. p = [1] and c = Config('radio', p). The field c.ports now points to the same list object as the caller’s variable p. No copy is made.

  2. c.ports = [9] raises FrozenInstanceError. This is rebinding, which freezing forbids.

  3. c.ports.append(2) succeeds. The list now holds [1, 2], and c.ports still points to the same list.

  4. p.append(3) also succeeds, and c.ports now shows [1, 2, 3]. The caller changed the contents of the frozen record without touching the record.

  5. hash(c) raises TypeError. The generated hash combines the hashes of the field values, and a list has no hash.

  6. c == Config('radio', [1, 2, 3]) is True. Equality compares field values, not object identity.

The repair stores an immutable copy. Declare ports: tuple and add a __post_init__ method whose body is object.__setattr__(self, 'ports', tuple(self.ports)); the ordinary assignment self.ports = ... would raise FrozenInstanceError even here. Now, with p = [1], Config('radio', p) holds the tuple (1,). A later p.append(3) leaves it unchanged, a tuple has no append method, and hash(c) returns a number. The record is now immutable all the way down, because neither a string nor a tuple of integers can change.

Stated precisely

Let a dataclass have the fields f1,…,fnf_1, \dots, f_n in declaration order, and let xx and yy be instances of it.

An instance is therefore immutable all the way down only when it is frozen and every field points to an object that cannot change: an integer, a string, bytes, a tuple or frozen set of such objects, or a frozen dataclass that meets the same condition.

Limits and common mistakes

The declared types are not checked. Config(name=5, ports='ab') succeeds. The annotation str records an intention for a static type checker, a separate program that examines code without running it (see the type hint entry), and has no effect while the program runs. Checks that must run belong in __post_init__.

Freezing is not a security barrier. object.__setattr__(c, 'name', 'x') rewrites a field of a frozen instance. Freezing protects against accidental assignment, not against code that intends to change the object.

Only an object that cannot change at any level can be shared without locks between threads, the parts of one program that run at the same time; see the immutable publication §9.24 entry.

The option unsafe_hash=True forces a generated hash on a record that is not frozen. If a field of such a record changes after the record has been stored in a dictionary or set, its hash changes, and lookups no longer find it.

The printed form shows every field, so a record that holds a password or a key prints it into any log that records the object. Declaring that field with field(repr=False) leaves it out.

A dataclass is not a serialization §4.28 format, a defined way to turn an object into bytes and back: dataclasses.asdict yields nested dictionaries, lists and tuples without class names.

Questions answered

Does frozen=True make every nested referenced object immutable?

No. frozen=True on a Python dataclass only stops the fields of the instance itself from being reassigned or deleted through ordinary attribute syntax: after c = Config('radio', [1]), the statement c.ports = [9] raises FrozenInstanceError. The objects that the fields point to keep their own behavior. c.ports.append(2) still changes the list, and any other code that holds a reference to the same list can change it too. Even the fields are protected only against ordinary assignment, because object.__setattr__ bypasses the block. An instance is immutable all the way down only when every field points to an object that cannot change, such as an integer, a string, a tuple of such values or another frozen dataclass that meets the same condition; convert mutable inputs in __post_init__, for example a list into a tuple.

Related entries: Type hint and Protocol (§12.46), Immutable publication (§9.24), Ownership (§4.2), Python (§12.23). Further reading: [118].