Less ceremony, clearer data.
Build small typed records and keep mutable defaults independent.
01 The idea
A dataclass generates common methods for a class whose main purpose is to hold named values. It can provide an initializer, a readable representation, and value-based equality. Type annotations describe the fields but do not validate incoming values. A default_factory creates a fresh mutable object for each instance.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
from dataclasses import dataclass, field
@dataclass
class Project:
name: str
tasks: list[str] = field(default_factory=list)
first, second = Project("Orbit"), Project("Atlas")
first.tasks.append("Build")
print(first)
print(second.tasks)Project(name='Orbit', tasks=['Build']) []
03 Under the hood
- 1
The generated initializer accepts name and optionally tasks. The generated repr shows field names and values, which is useful during development.
- 2
default_factory=list runs for each instance that needs a default. The two projects therefore do not share one task list.
- 3
frozen=True can prevent normal attribute reassignment but is not deep immutability. A list inside a frozen instance can still mutate, so choose immutable field types for a stricter record.
04 Your turn, builder
Define a frozen Point record and compare two points with equal coordinates.
Reveal one possible solution +
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
print(Point(2, 3) == Point(2, 3))05 Check your signal
Why use default_factory=list?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.