Hone

Lessons · Python · dataclasses

A dataclass writes the boilerplate for you

@dataclass reads the annotated fields and writes __init__, __repr__ and __eq__ for you. You declare what the object holds; Python writes how it is built, shown and compared.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Most classes in real code are records: a point, a row, a config, an event. Writing __init__ by hand for each is where typos and drift live. A dataclass is the same class with the tedium removed.

How to think about it

Ask: is this class mostly data with a few methods? Then make it a dataclass. Annotate each field with its type, give defaults after =, and add frozen=True when the values should never change.

Worked example

from dataclasses import dataclass
@dataclass
Writes __init__, __repr__ and __eq__.
class Point:
    x: int
A field, from the annotation.
    y: int = 0
A field with a default.
p = Point(3)
y falls back to 0.
print(p, p == Point(3, 0))
Point(x=3, y=0) True

Your turn

Turn the plain class into a dataclass.

from dataclasses import dataclass


class Order:
    item: str
    qty: int = 1

The trap

Treating the annotation as a check. count: int accepts a string without complaint; the types are documentation and tooling hints, not enforcement.

Practise dataclasses on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.