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?