Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Objects with purpose
EXPERIMENT 43 / 101

Less ceremony, clearer data.

Build small typed records and keep mutable defaults independent.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

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.

dataclasses.py
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)
↳ EXPECTED OUTPUT
Project(name='Orbit', tasks=['Build'])
[]

03 Under the hood

  1. 1

    The generated initializer accepts name and optionally tasks. The generated repr shows field names and values, which is useful during development.

  2. 2

    default_factory=list runs for each instance that needs a default. The two projects therefore do not share one task list.

  3. 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

A SMALL MISSION

Define a frozen Point record and compare two points with equal coordinates.

Reveal one possible solution +
one_possible_solution.py
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
    x: int
    y: int
print(Point(2, 3) == Point(2, 3))

05 Check your signal

QUICK SIGNAL CHECK

Why use default_factory=list?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.