typestar

Dataclasses, further in Python

frozen, slots, field factories and __post_init__.

from dataclasses import dataclass, field


@dataclass(frozen=True, slots=True, order=True)
class Result:
    tpm: float
    lang: str = "python"
    tags: tuple[str, ...] = ()


@dataclass
class Session:
    runs: list[Result] = field(default_factory=list)
    best: float = field(init=False, default=0.0)

    def __post_init__(self):
        self.best = max((r.tpm for r in self.runs), default=0.0)


a, b = Result(104.0), Result(98.0, "rust")
print(sorted([a, b])[0].lang, hash(a) is not None)
print(Session([a, b]).best)

How it works

  1. frozen=True makes instances hashable and immutable.
  2. field(default_factory=...) is how a mutable default is safe.
  3. __post_init__ runs after the generated init, for derived values.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
492
Tokens
159
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 91 seconds.

Type this snippet

Step 1 of 3 in Data & enums, step 45 of 53 in Pythonic Python.

← Previous Next →