Type Hints, Dataclasses & Modern Python
Lesson 6 of 6 · View course roadmap
Learn the idea
Modern professional Python is annotated and declarative. Two features define the style:
Type hints document what a function expects and returns — def price(qty: int, unit: float) -> float:. Python doesn't enforce them at runtime, but editors autocomplete with them and tools like mypy catch bugs before the code runs. Every major codebase now requires them.
Dataclasses kill boilerplate. Add @dataclass to a class of annotated fields and Python generates __init__, __repr__ and __eq__ for you:
- Fields can have defaults; mutable defaults use
field(default_factory=list) frozen=Truemakes instances immutable (hashable, safe to share)- They compose beautifully with type hints, sorting and serialization
This lesson caps the course: generators, decorators, dunders and dataclasses are the vocabulary of every senior Python code review.
Where you'll use this
Type hints are mandatory in most professional Python teams — mypy/pyright run in CI at Google, Meta, Stripe and Dropbox. Dataclasses (and their cousin pydantic) define API payloads, configs and domain models in nearly every modern service.
Common mistakes
- Mutable default fields:
tags: list = []raises ValueError in a dataclass — usefield(default_factory=list). - Assuming hints validate at runtime:
age: int = "forty"runs happily. Enforcement needs mypy or a validation library like pydantic. - Ordering fields wrong: fields with defaults must come after fields without, exactly like function parameters.
Pro tip
@dataclass(frozen=True, slots=True) gives you an immutable, hashable, memory-lean record type — the closest Python gets to a value type, perfect for keys, coordinates and money.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +50 XP
Define a @dataclass Book with fields title: str and pages: int. Create Book("Fluent Python", 792) and Book("Clean Code", 464) in a list, sort the list by page count, and print each as title (pages).
Clean Code (464) Fluent Python (792)
sorted(shelf, key=lambda book: book.pages) sorts ascending. Print with f"{book.title} ({book.pages})".
from dataclasses import dataclass
@dataclass
class Book:
title: str
pages: int
shelf = [Book("Fluent Python", 792), Book("Clean Code", 464)]
for book in sorted(shelf, key=lambda book: book.pages):
print(f"{book.title} ({book.pages})")
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.