8.3 Type Hints & Modern Python (mypy, Union | None & Protocol)
Write production-grade Python that teammates and IDEs love! Learn modern Python 3.10+ type hints, why they catch bugs BEFORE running code, and how TypedDict and Protocol work.
1. Why Add Type Hints to a Dynamically Typed Language?
Python is dynamically typed — so why do companies like Google, Meta, Instagram, and Stripe add Type Hints to almost every Python function?
Think of Type Hints as road signs and autocomplete superpowers:
- Catch bugs BEFORE running your code: Tools like
mypy,pyright, and VS Code's Pylance highlightTypeErrorbugs right in your editor! - Self-documenting code: Seeing
def get_user(user_id: int) -> dict[str, str] | None:tells you everything in 1 second without reading the function body. - Instant IDE autocomplete: VS Code knows every method on your variables.
Important Fact: Python ignores type hints at runtime — they add zero performance penalty and never crash your program on their own!
2. Modern Python 3.10+ Type Hint Cheat Sheet
from typing import Any, Callable, TypedDict, Protocol
# 1) Basic types & built-in generics (Python 3.9+ — no need for typing.List!)
age: int = 25
scores: list[int] = [90, 85, 92]
prices: dict[str, float] = {"tea": 4.5, "milk": 3.0}
# 2) Optional values using `|` (Python 3.10+ — replaces Optional[str])
def find_email(user_id: int) -> str | None:
return "riya@example.com" if user_id == 1 else None
# 3) TypedDict — give exact key types to JSON-like dicts!
class UserPayload(TypedDict):
id: int
name: str
is_admin: bool
# 4) Protocol — Static Duck Typing! Any class with .pay() matches!
class Payable(Protocol):
def pay(self, amount: float) -> str: ...
3. Running Static Type Checks (mypy)
pip install mypy
mypy app.py
# Success: no issues found in 1 source file
4. Interactive Trace: Typed Function & None Guard
Quick Quiz: Module 8.3 — Type Hints & Modern Python
Keep Exploring: Related Lessons & Tools
All Courses →Validate, prettify, minify, sort keys, explore interactive collapsible JSON trees, and generate TypeScript interfaces instantly.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.