Type hints and dataclasses
More Python10 min readLesson 6 of 7
6.1 Hints are documentation for people and tools
Python does not enforce type hints at runtime, but editors and tools like mypy use them to catch mistakes before a program runs. Start with function signatures and data shapes; precise annotation of every local variable is rarely worth it.
A dataclass generates __init__, __repr__ and equality from annotated fields. It is the shortest sensible way to define a small record such as a lesson or a timetable block.
from dataclasses import dataclass
@dataclass
class Lesson:
title: str
minutes: int = 8
lesson = Lesson("Loops", 12)
print(lesson)
print(lesson.minutes)Output
Lesson(title='Loops', minutes=12) 12
Use list[str] and dict[str, int] for containers. Optional values are str | None (Python 3.10 and newer). A dataclass with frozen=True becomes immutable, which is useful for values that should not be changed after creation.
