Python · Module 08: Intermediate & Modern PythonTutorial 24 of 30
All Tutorials·~1.5 hrs

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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:

  1. Catch bugs BEFORE running your code: Tools like mypy, pyright, and VS Code's Pylance highlight TypeError bugs right in your editor!
  2. 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.
  3. 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

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

BASH
pip install mypy
mypy app.py
# Success: no issues found in 1 source file

4. Interactive Trace: Typed Function & None Guard

Tracing a Typed Discount Helper with str | None Safety
Interactive Line-by-Line Execution Trace · Step 1 of 4
1def apply_coupon(price: float, code: str | None) -> float:
2 if code == "SAVE10":
3 return round(price * 0.9, 2)
4 return price
5→total = apply_coupon(200.0, "SAVE10")
6print(total)
Variables in Memory
price200.0float
code"SAVE10"str
Console Output
(nothing printed yet)
What just happened: Type hints clearly tell callers that code can be either a str or None.

Quick Quiz: Module 8.3 — Type Hints & Modern Python

Q1.What happens at RUNTIME if you pass a string into `def add(a: int, b: int) -> int:`?
Q2.In Python 3.10+, what does `def get_user(id: int) -> dict | None:` mean?
Q3.Which tool checks your Python type hints BEFORE you run your code?

Keep Exploring: Related Lessons & Tools

All Courses →