Dataclass features in Python
Beyond the basics: ordering, defaults, and frozen data.
from dataclasses import dataclass, field
@dataclass(order=True)
class Task:
priority: int
title: str = "untitled"
tags: list[str] = field(default_factory=list)
@dataclass(frozen=True)
class Config:
host: str
port: int = 8080
urgent = Task(1, "ship it", tags=["release"])
later = Task(5)
ordered = sorted([later, urgent])
How it works
@dataclass(order=True)derives comparison methods.field(default_factory=list)avoids shared mutable defaults.frozen=Truemakes instances immutable.
Keywords and builtins used here
ConfigTaskclassintlistsortedstr
The run, in numbers
- Lines
- 19
- Characters to type
- 326
- Tokens
- 89
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 51 seconds.
Step 2 of 4 in Typing & dataclasses, step 21 of 53 in Pythonic Python.