▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Type hints
Annotate code and catch bugs early with mypy.
🎬 Video version coming soon — read it now
Type hints label what types variables, parameters and return values should be. Python doesn't enforce them at runtime, but editors and tools use them to catch bugs before you run the code.
The basics
Optional and union types
X | None means "an X, or None". You'll see the older style Optional[X] from typing in existing code; it means the same thing.
More useful types
Why bother?
- Editors (VS Code with Pylance) underline mistakes as you type and autocomplete much better
- Readers know what a function expects without reading its body
- Tools like FastAPI and Pydantic use hints to validate data automatically. You saw this with
messages.parsein Python Meets AI
Checking with mypy
mypy reads your hints and reports mismatches across the whole project, much like a teacher checking a test before you hand it in. Many teams run it automatically before code is merged.
How much to annotate
- Always: function parameters and return types in code others will use
- Usually not: local variables, where the type is obvious from the value
- Gradually: you can add hints to an existing project one file at a time
In one line
Type hints document expected types; Python ignores them at runtime, but editors, mypy and libraries like Pydantic use them to catch bugs early.
Share with a friend