Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Type Hints, Dataclasses & Modern Python

18 min 50 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 6 of 6 · View course roadmap
Step 1

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=True makes 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 — use field(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.

Step 2

Try it yourself

Blank · autosaved

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”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +50 XP

Blank · autosaved

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).

Target output
Clean Code (464)
Fluent Python (792)
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. What does Python do with type hints at runtime?
2. Which methods does @dataclass generate from the field annotations?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path