Python Ignores Type Hints at Runtime, So Only a Checker or a Library Enforces Them

In progress

def get_root(number: int) -> float documents intent, but the interpreter runs get_root("9") without complaint until the arithmetic fails. Hints are metadata. They become rules only when something reads them: a static checker such as mypy before the code runs, or a library such as Pydantic (and through it FastAPI) that validates data against them at runtime.

The Syntax That Matters Day to Day

def get_root(number: int | float) -> float: ...
def greet(name: str | None = None) -> str: ...

digits: list[int]
city: tuple[str, float]
vehicle: dict[str, str | int]
handler: Callable[..., None]
anything: Any          # opts out of checking

Built-in generics (list[int]) work from Python 3.9, the | union from 3.10; older code uses List, Optional and Union from typing.

Who Reads the Hints

Reader When What it does
mypy, pyright before running, in the editor or CI reports calls and returns that don't match
Pydantic at runtime, when a model is created validates and converts data, raises a detailed error
FastAPI per request uses hints to decide where each parameter comes from and to validate it with Pydantic
The interpreter never stores them in __annotations__ and moves on
from pydantic import BaseModel, EmailStr

class UserCreate(BaseModel):
    username: str
    email: EmailStr     # needs the email-validator extra
    age: int

UserCreate(username="sam", email="sam@example.com", age="32")   # age converted to 32
UserCreate(username="sam", email="not-an-email", age="x")       # ValidationError, two errors

References

Review cards

Flashcard Why do Python type hints not enforce type checking at runtime?

Python's interpreter does not perform type checking at runtime; it only stores type hints in __annotations__ and ignores them during execution.

Flashcard Who actually reads Python type hints, and when?

mypy or pyright before the code runs; Pydantic (and FastAPI through it) at runtime when it validates data. The interpreter only stores them in annotations.

Flashcard What happens when a client sends invalid data to a FastAPI endpoint?

Pydantic validation fails and FastAPI answers 422 with a JSON list of the errors. The endpoint function never runs.