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
frozen=Truemakes instances hashable and immutable.field(default_factory=...)is how a mutable default is safe.__post_init__runs after the generated init, for derived values.
Keywords and builtins used here
ResultSession__post_init__classdeffloatforhashlistmaxprintselfsortedstrtuple
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.
Step 1 of 3 in Data & enums, step 45 of 53 in Pythonic Python.