typestar

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

  1. @dataclass(order=True) derives comparison methods.
  2. field(default_factory=list) avoids shared mutable defaults.
  3. frozen=True makes instances immutable.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 4 in Typing & dataclasses, step 21 of 53 in Pythonic Python.

← Previous Next →