Dataclasses and Record Ownership
Data Classes in Python 3.7
BOTIE
The generated methods reduce that repetitive work while leaving an ordinary Python class. Field annotations identify the structure, but do not validate supplied values. Mutable fields still need an ownership decision, and a frozen instance restricts attribute assignment rather than freezing every object reachable through it.
Sources for this history
Why Did Tagging One Report Change Another?
Botie starts a report for each greenhouse. Each report needs a name, a reading and an initially empty list of notes. After adding a note to the north greenhouse, the south report shows the same note. The two reports were given references to one shared list.
A recurring record benefits from a clear structure, but a class name alone does not establish who owns its data. We will build a named record, decide which values it accepts and give each report the mutable state it is supposed to own.
The records illustrate the ownership of mutable defaults; they are not Python dataclass instances and do not validate Python annotations. Each run uses a private copy so repeated tests leave the source data unchanged.
Step 1 of 1
Give each report its own list
Adding a note to one greenhouse should leave the other greenhouse unchanged.
| Report | List ownership | After tagging north |
|---|---|---|
| north | a separate list | ["checked"] |
| south | another separate list | [] |
| both sharing one list | one list reached through two names | the note appears through both names |
north
- List ownership
- a separate list
- After tagging north
- ["checked"]
south
- List ownership
- another separate list
- After tagging north
- []
both sharing one list
- List ownership
- one list reached through two names
- After tagging north
- the note appears through both names
Give a recurring record a named type
A separately created list belongs to each report, so adding north's note leaves south's notes alone.
Keep Each Report's Notes Separate
A greenhouse report has a name and a list of notes called tags. With only one report, reusing one empty notes list appears to work. A second report lets us see whether that list belongs to one greenhouse or is shared between them.
BOTIE
Reports with independent note lists
- house
- north
- tags
- ["checked"]
| house | tags |
|---|---|
| north | ["checked"] |
Follow the operations
1. Greenhouses needing reports
- 0north
2. Create the notes lists
[ [] ]
3. Attach notes to their reports
- house
- north
- tags
- []
house tags north [] 4. Greenhouse receiving the note
north
5. Note to add
checked
6. Add a note to one greenhouse
- house
- north
- tags
- ["checked"]
house tags north ["checked"] 7. Result
- house
- north
- tags
- ["checked"]
house tags north ["checked"]
The records illustrate the ownership of mutable defaults; they are not Python dataclass instances and do not validate Python annotations. Each run uses a private copy so repeated tests leave the source data unchanged.
1. Give a recurring record a named type
A class defines a kind of object. Calling it creates an instance, and attributes hold that instance’s values. The self parameter names the particular instance whose method is running.
A dictionary is still useful for flexible records. A named class becomes helpful when the same fields and related behavior recur across an interface.
A constructor establishes an object’s initial state. It does not automatically establish every application invariant.
Create an ordinary record object
This class explicitly assigns two instance attributes.
class Reading:
def __init__(self, house, temperature_c):
self.house = house
self.temperature_c = temperature_c
reading = Reading("north", 12.0)
print(reading.house, reading.temperature_c)north 12.0Each call can create another Reading with its own attribute values.
2. Let dataclass generate routine methods
The @dataclass decorator processes a class after its definition. It uses annotated fields to generate an initializer and useful methods such as a representation and equality comparison.
This saves repeated field-handling code. It does not inspect every supplied value against its annotation. An explicit validation boundary is still needed when the record must reject an invalid name or measurement.
The decorator adds methods to a class; it is not a runtime schema validator.
Declare the same fields once
The dataclass creates the initializer and a representation from the declared fields.
from dataclasses import dataclass
@dataclass
class Reading:
house: str
temperature_c: float
first = Reading("north", 12.0)
second = Reading("north", 12.0)
print(first)
print(first == second)Reading(house='north', temperature_c=12.0)
TrueThese instances compare by their declared field values, while remaining separate objects.
Check yourself
Questions on Parts 1 to 2
Question 1 of 2
Does construction automatically reject a string in temperature_c?
Question data
@dataclass
class Reading:
temperature_c: float
No explicit validation is defined.3. Make required invariants explicit
An invariant is a condition the object is expected to satisfy throughout its intended use. A reading may require a nonempty name and a finite numerical temperature. Write those checks rather than assuming the annotations enforce them.
A dataclass’s generated initializer calls __post_init__ when that method is present. It is one place to check the newly supplied field values. If later mutation can break the same condition, the design must account for that too.
Validation establishes a particular agreement. Choosing frozen fields is a separate control on later assignment.
Reject an unsuitable field explicitly
This class validates a finite threshold in its post-initialization hook.
from dataclasses import dataclass
import math
@dataclass
class Threshold:
limit_c: float
def __post_init__(self):
if type(self.limit_c) not in (int, float) or (type(self.limit_c) is float and not math.isfinite(self.limit_c)):
raise ValueError("limit_c must be a finite number")
print(Threshold(20).limit_c)
try:
Threshold("warm")
except ValueError:
print("rejected")20
rejectedThe explicit check rejects the string. The field annotation alone would not do that.
4. Create mutable defaults separately
An empty list should usually belong to one report. field(default_factory=list) calls list separately when a caller omits that field, producing independent empty lists.
A default factory does not copy a list that a caller explicitly supplies. If the object promises to own an independent copy, establish that ownership explicitly. A shallow list copy separates the outer list but still shares any nested mutable objects.
Default creation and copying supplied data are different responsibilities.
Start two reports independently
One report can gain a tag without changing the other report.
from dataclasses import dataclass, field
@dataclass
class Report:
house: str
tags: list[str] = field(default_factory=list)
north = Report("north")
south = Report("south")
north.tags.append("checked")
print(north.tags)
print(south.tags)['checked']
[]The factory was called separately for the two omitted tag fields.
5. Know what frozen restricts
frozen=True rejects ordinary rebinding of dataclass attributes. It is useful for a record whose field assignments should remain fixed after construction.
It does not recursively freeze a list stored in a field. Use immutable field values, such as tuples of immutable items, when the record’s intended behavior requires that stronger property. Frozen is also not a security boundary against code deliberately bypassing normal attribute access.
Choose the record’s mutation policy from its actual callers rather than adding frozen everywhere.
A frozen field can still refer to a mutable object
The field still points to the same list, but that list’s contents can change.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Snapshot:
tags: list[str] = field(default_factory=list)
snapshot = Snapshot()
snapshot.tags.append("reviewed")
print(snapshot.tags)['reviewed']The append changes the referenced list rather than assigning a different list to the tags attribute.
Check yourself
Questions on Parts 1 to 5
Question 1 of 4
Frozen guarantees that the nested list cannot change.
Question data
A frozen dataclass has a list field. The program calls instance.tags.append("checked").Try it with Botie
Build with Botie
Write and run Python