L5Β·Intermediate/Advanced
π·οΈTyping & Dataclasses
Static type hints and boilerplate-free classes.
typingdataclasshints
Β§ 1Hints
def f(x: int) -> str: β not enforced at runtime. Tools like mypy/pyright check them.
Β§ 2Modern generics (3.9+)
list[int], dict[str, int]. Union: X | Y. Optional: X | None.
Β§ 3@dataclass
Auto-generates __init__, __repr__, __eq__ from field annotations.
Example
1from dataclasses import dataclassβ2β3@dataclassβ4class Point:β5 x: floatβ6 y: floatβ7 def dist(self) -> float:β8 return (self.x**2 + self.y**2) ** 0.5β9β10print(Point(3, 4))β11print(Point(3, 4).dist())βTry it live Β· Python runs in your browser
Loading playgroundβ¦
Checkpoint quiz
Question 1 / 2
Are Python type hints enforced at runtime?