Appearance
3.13.12 — Type Hints & Static Typing
A refactor renames a field from customer["name"] to customer["full_name"]. In a codebase of two hundred thousand lines, finding every place that still reads "name" takes a week of searching and a month of production bugs. In TypeScript (3.7), the compiler would list every broken line in seconds. Python has the same capability, built a different way: optional type hints that a separate tool checks before the code runs. This page tells the story of how typing came to a dynamic language, then covers every typing feature a senior engineer is expected to use. It finishes with the part that makes FastAPI possible: reading those hints at run time to validate data.
1. The story: types added to a language that had none
Python was designed in 1989 as a dynamically typed language. A variable is a label that can point at any object (3.13.2), and errors such as adding a string to a number are found only when that line runs. For scripts that was fine. For codebases with hundreds of engineers, it became painful.
The change came in steps.
- 2006, PEP 3107. Python 3 added function annotations: syntax for attaching any expression to a parameter or return value, with no meaning defined. The idea was to let the community experiment.
- 2012, mypy. Jukka Lehtosalo, a PhD student at Cambridge, built mypy, a checker that reads annotations as types and reports errors without running the code. Guido van Rossum joined the effort.
- 2014, PEP 484. The
typingmodule was standardised, giving one shared meaning to annotations. Dropbox, then Guido's employer, used mypy to check over four million lines of Python. - Since then, one step at a time. Variable annotations arrived in 2016 (PEP 526). Structural
Protocols followed (PEP 544). In 2020,list[int]stopped needing an import (PEP 585), andint | Nonebecame valid (PEP 604). A cleaner generics syntax came in 2023 (PEP 695). Lazily evaluated annotations came in 2025 (PEP 649).
Today several checkers exist. mypy is the original. Pyright, from Microsoft, powers VS Code's Pylance and is very fast. Newer Rust-based checkers are appearing too. All of them read the same standard hints.
2. The most important fact: Python does not enforce hints
This surprises everyone coming from Java or TypeScript, so it comes first.
python
def apply_discount(price: int, percent: int) -> int:
return price * (100 - percent) // 100
print(apply_discount(450, 10)) # (1)
print(apply_discount.__annotations__) # (2)
try:
apply_discount("ab", 2) # (3)
except TypeError as error:
print("TypeError:", error)text
405
{'price': <class 'int'>, 'percent': <class 'int'>, 'return': <class 'int'>}
TypeError: unsupported operand type(s) for //: 'str' and 'int'(1)Normal use.(2)The hints are stored on the function as plain data, nothing more.(3)Python happily calls the function with a string."ab" * 98even works, building a long string. The crash happens one step later, inside the function, with an error that says nothing about the wrong argument.
So in Python, type hints are for tools, not for the interpreter. Three kinds of tool read them.
- Static checkers such as mypy and Pyright, which read your code without running it and report mistakes.
- Editors, which use them for autocomplete, go-to-definition and safe renames.
- Run-time libraries such as Pydantic and FastAPI, which read the hints while the program runs and choose to enforce them. Section 7 shows how.
Here is what a checker says about the same mistake, before anything runs.
text
$ mypy --strict checkout.py
checkout.py:8: error: Argument 1 to "apply_discount" has incompatible type "str"; expected "int" [arg-type]This is the same erasure model as TypeScript (3.7.1): types are checked by a separate tool and have no effect on how the program runs. The difference is that TypeScript's types are deleted by the compiler, while Python's annotations stay on the objects, where libraries can read them.
3. The everyday vocabulary
Built-in types and collections
Since Python 3.9, built-in collection types can be used directly in hints.
python
def total_paise(prices: list[int]) -> int: ...
def stock_levels() -> dict[str, int]: ...
def location() -> tuple[float, float]: ... # (1) exactly two floats
def line_items() -> tuple[str, ...]: ... # (2) any number of strings
def unique_skus() -> set[str]: ...(1)A tuple hint lists the type of each position.(2)...means "any length, all of this type".
For parameters, prefer the most general type that works. A function that only loops over its input should accept Iterable[str] from collections.abc, not list[str], so callers can pass a list, a set, a tuple or a generator. For return values, be specific, so callers know exactly what they get.
None, unions and optional values
X | Y means "either type". The most common union by far is X | None, which means "might be missing".
python
def find_customer(email: str) -> dict[str, str] | None:
...
customer = find_customer("asha@example.com")
print(customer["name"]) # (1)text
checkout.py:5: error: Value of type "dict[str, str] | None" is not indexable [index](1)The checker refuses, becausecustomermight beNone.
This is the single most valuable thing a type checker does: it finds every place you forgot that a value might be missing. You fix it the same way as in TypeScript (3.7.3), by narrowing: checking the value so the checker can see that it is safe.
python
customer = find_customer("asha@example.com")
if customer is None:
raise LookupError("no such customer")
print(customer["name"]) # (1) fine: customer is now dict[str, str]The checker follows if, isinstance, is None and early return/raise to narrow types, just like TypeScript's control-flow analysis. Older code writes Optional[X] from typing, which means exactly X | None.
Literal, Final and Any
python
from typing import Literal, Final, Any
Status = Literal["pending", "paid", "shipped"] # (1)
def mark(status: Status) -> None: ...
mark("payed") # (2)
MAX_ITEMS: Final = 50 # (3)
MAX_ITEMS = 60
def legacy(payload: Any) -> None: ... # (4)text
checkout.py:7: error: Argument 1 to "mark" has incompatible type "Literal['payed']"; expected "Literal['pending', 'paid', 'shipped']" [arg-type]
checkout.py:10: error: Cannot assign to final name "MAX_ITEMS" [misc](1)Literalallows only these exact values. It is lighter than anEnum(3.13.8), and works well for small sets of strings.(2)The typo is caught.(3)Finalmeans "never reassign this".(4)Anyturns checking off for that value: every operation on it is allowed. It is an escape hatch for code that cannot be typed yet. EachAnyis a hole in your safety net.objectis the safe alternative when you mean "any value, but I will check it before using it".
Type aliases and NewType
python
type OrderId = str # (1)
type Pair[K, V] = tuple[K, V] # (2)
from typing import NewType
CustomerId = NewType("CustomerId", int) # (3)
def load_customer(customer_id: CustomerId) -> None: ...
load_customer(CustomerId(42)) # fine
load_customer(42) # (4) checker error(1)Thetypestatement, added in Python 3.12, creates an alias: a second name for a type.OrderIdandstrare completely interchangeable.(2)Aliases can take type parameters.(3)NewTypecreates a distinct type for the checker. At run timeCustomerId(42)is just the integer42, at zero cost.(4)A plainintis rejected where aCustomerIdis expected. That prevents passing an order ID where a customer ID belongs. It is the same idea as the "branded types" trick in TypeScript (3.7.7).
4. Generics
A generic function or class works with many types while keeping track of which one. Without generics, a function returning the first item of a list would have to return Any, and the caller would lose all type information. Python 3.12 added a clean syntax for this, described in PEP 695.
python
def first[T](items: list[T]) -> T: # (1)
return items[0]
reveal_type(first([450, 40])) # (2)
reveal_type(first(["mug", "pen"]))
class Page[T]: # (3)
def __init__(self, items: list[T], next_cursor: str | None) -> None:
self.items = items
self.next_cursor = next_cursor
orders: Page[str] = Page(["ORD-1", "ORD-2"], next_cursor="abc") # (4)text
checkout.py:4: note: Revealed type is "int"
checkout.py:5: note: Revealed type is "str"(1)[T]after the name declares a type parameter: a placeholder that is filled in at each call. "Given a list ofT, return aT."(2)reveal_typeis a special function that only type checkers understand. The checker filledTwithintfor this call andstrfor the next.(3)A generic class. Every method can useT.(4)A paginated API response holding strings.Page[Order]would holdOrderobjects, with full checking either way.
You can restrict a type parameter. def cheapest[T: Priced](items: list[T]) -> T accepts only types that match Priced, the same idea as extends in TypeScript (3.7.4). Older code declares type parameters with T = TypeVar("T") at module level. The meaning is the same.
Self
A method that returns its own instance, as in a builder, should return the subclass when called on a subclass. Self says exactly that.
python
from typing import Self
class QueryBuilder:
def where(self, condition: str) -> Self: # (1)
return self
class OrderQuery(QueryBuilder):
pass
reveal_type(OrderQuery().where("total > 100"))text
checkout.py:10: note: Revealed type is "checkout.OrderQuery"(1)Had the return type beenQueryBuilder, chaining on anOrderQuerywould lose its subclass methods.
Callable and ParamSpec
Callable[[int, str], bool] describes a function that takes an int and a str and returns a bool. For decorators, which must keep the wrapped function's exact parameters, Python has ParamSpec. 3.13.5 showed the full pattern: def timed[**P, R](func: Callable[P, R]) -> Callable[P, R]. The **P captures a whole parameter list, so the decorated function keeps its checked signature.
5. Structural typing with Protocol
3.13.6 used an abstract base class to say "a payment gateway must have charge". That requires inheritance. But Python has always worked by duck typing: if an object has the right methods, it works, whatever its class. Protocol, added in Python 3.8 by PEP 544, lets the checker understand duck typing. A class matches a protocol if it has matching methods, without inheriting from it. This is structural typing, exactly like TypeScript's interfaces (3.3).
python
from typing import Protocol
class Notifier(Protocol): # (1)
def send(self, to: str, message: str) -> None: ...
class EmailSender: # (2)
def send(self, to: str, message: str) -> None:
print(f" email to {to}: {message}")
class SmsSender:
def send(self, to: str) -> None: ... # (3)
def notify(channel: Notifier) -> None:
channel.send("asha@example.com", "Order shipped")
notify(EmailSender())
notify(SmsSender())text
email to asha@example.com: Order shipped
TypeError: SmsSender.send() takes 2 positional arguments but 3 were giventext
checkout.py:17: error: Argument 1 to "notify" has incompatible type "SmsSender"; expected "Notifier" [arg-type]
checkout.py:17: note: Following member(s) of "SmsSender" have conflicts:
checkout.py:17: note: Expected:
checkout.py:17: note: def send(self, to: str, message: str) -> None
checkout.py:17: note: Got:
checkout.py:17: note: def send(self, to: str) -> None(1)The protocol describes a shape: "has asend(to, message)method".(2)EmailSendernever mentionsNotifier, but it has the right method, so it fits.(3)SmsSenderhas asendwith the wrong parameters. At run time Python would crash only when that line ran. The checker explains the mismatch precisely, before anything runs.
Protocols are ideal for the boundaries in a service. Your order logic depends on "something that can send", and production code, a sandbox gateway or a third-party library class can all fit, without importing your base class. Part 9 builds on this heavily.
By default protocols are for checkers only. Adding @runtime_checkable makes isinstance(obj, Notifier) work at run time, but that check only confirms the method names exist, not their parameters.
TypedDict and overloads
TypedDict (3.13.8) types the keys of a plain dict, which is how JSON-shaped data is usually typed when it must stay a dict.
@overload describes a function whose return type depends on its argument type. You write several signatures with no bodies for the checker, then one real implementation.
python
from typing import overload
@overload
def parse_amount(raw: str) -> int: ...
@overload
def parse_amount(raw: None) -> None: ...
def parse_amount(raw: str | None) -> int | None: # (1)
return None if raw is None else int(raw)
reveal_type(parse_amount("450"))
reveal_type(parse_amount(None))text
checkout.py:10: note: Revealed type is "int"
checkout.py:11: note: Revealed type is "None"(1)Only this last definition exists at run time. The overloads tell the checker that a string in means an int out, so callers never have to check forNoneafter passing a string.
Custom narrowing with TypeIs
When your own function does the checking, tell the checker what it proves. TypeIs, added in Python 3.13, plays the same role as TypeScript's x is T predicates.
python
from typing import TypeIs
def is_sku_list(values: list[object]) -> TypeIs[list[str]]: # (1)
return all(isinstance(value, str) for value in values)
def import_skus(raw: list[object]) -> None:
if is_sku_list(raw):
print(", ".join(raw)) # (2)(1)If this returnsTrue, the argument is alist[str].(2)So inside theif,", ".join(raw)type-checks.
6. Hints that need care at run time
TYPE_CHECKING: imports only the checker sees
typing.TYPE_CHECKING is False when the program runs and treated as True by checkers. Imports placed under it cost nothing at run time and cannot cause circular imports (3.13.11).
python
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from shop.orders import Order # (1) never imported at run time
class Customer:
def latest_order(self) -> Order: # (2)
...(1)Checkers read this import. The interpreter skips it.(2)So how can the annotation nameOrderwithout crashing? The answer is in the next section.
Annotations are evaluated lazily in Python 3.14
Before 3.14, annotations were evaluated when the def ran. Naming a class that was defined later, or only imported under TYPE_CHECKING, raised NameError. People worked around it by writing annotations as strings, -> "Order", or with from __future__ import annotations. Python 3.14 implemented PEP 649: annotations are now evaluated only when someone asks for them.
python
class Customer:
def latest_order(self) -> Order: # (1) Order is not defined yet
return Order(self)
class Order:
def __init__(self, customer: Customer) -> None:
self.customer = customer
print(Customer.latest_order.__annotations__) # (2)text
{'return': <class '__main__.Order'>}(1)In 3.13 this line raisedNameError. In 3.14 nothing is evaluated here.(2)Reading__annotations__evaluates them now, whenOrderexists.
If a name truly does not exist, for example because it was only imported under TYPE_CHECKING, reading __annotations__ raises NameError. The new annotationlib module can return the annotations as forward references or as strings instead.
python
import annotationlib
def ship(order: MissingType) -> None: ...
print(annotationlib.get_annotations(ship, format=annotationlib.Format.STRING))text
{'order': 'MissingType', 'return': 'None'}That matters for libraries like Pydantic and FastAPI, which do read annotations at run time. For them, a type used in a model or endpoint must be importable at run time, not only under TYPE_CHECKING.
7. Reading hints at run time: how FastAPI and Pydantic use them
Here is the connection to Chapter 3.14. Libraries read hints with three functions from typing.
get_type_hints(obj)returns the evaluated annotations of a function or class.get_origin(hint)returns the "outer" type:listforlist[int],AnnotatedforAnnotated[int, ...].get_args(hint)returns the inner parts:(int,)forlist[int],(int, NoneType)forint | None.
python
from typing import Annotated, get_type_hints, get_origin, get_args
print(get_origin(list[int]), get_args(dict[str, int]), get_args(int | None))text
<class 'list'> (<class 'str'>, <class 'int'>) (<class 'int'>, <class 'NoneType'>)Annotated: attaching extra information to a type
Annotated[T, extra, ...] means "the type is T, and here is some extra information". Checkers see only T and ignore the extras. Run-time libraries read the extras. This one feature, added in Python 3.9 by PEP 593, is how FastAPI says "this int comes from the query string and must be at least 1".
Here is a tiny version of what Pydantic and FastAPI do, built from these pieces: a decorator that validates arguments using their hints.
python
import functools
import inspect
from typing import Annotated, get_type_hints, get_origin, get_args
class Min: # (1)
def __init__(self, value: int) -> None:
self.value = value
def validate_call(func):
hints = get_type_hints(func, include_extras=True) # (2)
signature = inspect.signature(func)
@functools.wraps(func)
def wrapper(*args, **kwargs):
bound = signature.bind(*args, **kwargs) # (3)
for name, value in bound.arguments.items():
hint = hints.get(name)
extras = ()
if get_origin(hint) is Annotated: # (4)
hint, *extras = get_args(hint)
if not isinstance(value, hint):
try:
value = hint(value) # (5)
except (TypeError, ValueError):
raise TypeError(f"{name}: expected {hint.__name__}, got {value!r}") from None
for rule in extras:
if isinstance(rule, Min) and value < rule.value:
raise ValueError(f"{name}: must be at least {rule.value}, got {value}")
bound.arguments[name] = value
return func(*bound.args, **bound.kwargs)
return wrapper
@validate_call
def add_to_cart(sku: str, quantity: Annotated[int, Min(1)]) -> str:
return f"{quantity} x {sku}"
print(add_to_cart("mug", "3")) # (6)
for bad in (0, "three"):
try:
add_to_cart("mug", bad)
except (TypeError, ValueError) as error:
print(type(error).__name__, error)text
3 x mug
ValueError quantity: must be at least 1, got 0
TypeError quantity: expected int, got 'three'(1)A marker object, carrying a rule, that will live insideAnnotated.(2)Read the hints once, at decoration time.include_extras=Truekeeps theAnnotatedwrapper instead of stripping it.(3)inspect.signature(...).bindmatches the call's arguments to parameter names, exactly as Python itself would (3.13.4).(4)SplitAnnotated[int, Min(1)]into the real type and its extras.(5)Try to convert the value, so the string"3"becomes the integer3. Query strings and form fields always arrive as text, so a web framework must do this.(6)Conversion and validation happened from nothing but the function's hints.
This is, in miniature, exactly what FastAPI does for every endpoint. It reads your function's signature and hints once at start-up, builds a plan for each parameter, and on every request converts and validates the incoming data before calling your function. Pydantic does the same for model fields, with a fast Rust core and far richer rules. 3.14.2 and 3.14.3 take it from here.
8. Adopting typing in a real codebase
- Start with function signatures at module boundaries: public functions, service methods, API handlers. Local variables are usually inferred.
- Run the checker in CI so new errors cannot be merged. Start in a lenient mode on old code and turn on
--strictmodule by module, the same "strictness ratchet" as TypeScript in 3.7.7. - Ban new
Anyand useobjectplus narrowing instead. - Validate at the edges. Hints prove that your own code is consistent. They prove nothing about the JSON a client sends you. That is Pydantic's job at the boundary.
What the interviewer will push on
"Does Python enforce type hints?" No. The interpreter stores them and ignores them. They are checked by static tools such as mypy and Pyright, used by editors, and optionally enforced at run time by libraries such as Pydantic and FastAPI. The tell is explaining that last group and how it reads hints with get_type_hints.
"What is the difference between a Protocol and an abstract base class?" An ABC is nominal: a class must inherit from it. A protocol is structural: any class with matching methods fits. Mention @runtime_checkable and that its isinstance only checks method names.
"How do you type a decorator so it keeps the wrapped function's signature?" ParamSpec and a return type variable: def deco[**P, R](f: Callable[P, R]) -> Callable[P, R], with *args: P.args, **kwargs: P.kwargs in the wrapper, plus functools.wraps.
"What is Annotated for?" Attaching metadata that checkers ignore and run-time libraries read. FastAPI's Annotated[int, Query(ge=1)] and Pydantic's field constraints both use it.
"How do you avoid circular imports caused by type hints?" if TYPE_CHECKING: imports, plus lazy annotations in 3.14, or string annotations and from __future__ import annotations in older versions. Warn that run-time readers such as Pydantic need the real type to be importable.
Something to volunteer that nobody asks for: in Python 3.14, annotations are evaluated lazily (PEP 649), so forward references no longer need quotes, and annotationlib can return annotations as strings or forward references. Knowing what changed in the latest release signals that you follow the language, not just use it.
Recall
- Type hints are stored in
__annotations__and not enforced by the interpreter. Static checkers (mypy, Pyright), editors and run-time libraries (Pydantic, FastAPI) read them. - History: PEP 3107 annotations (2006), mypy (2012), PEP 484
typing(2014), PEP 585/604list[int]andX | None(2020), PEP 695 generics syntax (3.12), PEP 649 lazy annotations (3.14). X | Noneplus narrowing withis None,isinstanceand early returns.Literalfor fixed values,Finalfor constants,Anyturns checking off,objectis the safe "anything".type Alias = ...for aliases,NewTypefor distinct IDs at zero cost. Generics withdef f[T](...)andclass C[T].Selffor builders.ParamSpecfor decorators.@overloadfor argument-dependent return types.TypeIsfor custom checks.Protocol= structural typing, like TypeScript interfaces.@runtime_checkablechecks only method names.TYPE_CHECKINGimports exist only for checkers. 3.14 evaluates annotations lazily, andannotationlibcan read them as strings.- Run-time reading:
get_type_hints(include_extras=True),get_origin,get_args.Annotated[T, extra]carries rules for libraries. That is how FastAPI converts and validates parameters.
Self-test: What does Python do with def f(x: int) when called with a string? Why does a checker reject customer["name"] after a function returning dict | None? What is the difference between an alias and a NewType? How does a library find the Min(1) inside Annotated[int, Min(1)]?
Quiz Bank
FoundationalWhat is the difference between Any and object as a type hint?
Both accept any value, but they mean opposite things to the checker. Any switches checking off: you can call any method or pass the value anywhere, and errors are not reported. object is the honest "could be anything": the checker allows only operations that every object supports, so you must narrow it with isinstance or another check before using it as something specific. Use object for genuinely unknown input, and treat each Any as a temporary hole to fill later.
AppliedYour Pydantic model works in tests but crashes at startup with NameError after you moved an import under if TYPE_CHECKING. Why?
TYPE_CHECKING is False at run time, so the import never happens, and the name exists only for static checkers. Pydantic builds its validators by reading the model's annotations at run time with get_type_hints-style evaluation, so it must resolve the name and fails. Static-only imports are fine for annotations that nothing reads at run time. For types used in Pydantic models, FastAPI endpoints or dependencies, keep a real import, and fix any circular import by restructuring modules instead.
InterviewWrite a generic function that returns the item with the highest value of a numeric attribute, typed so callers keep the exact item type.
python
from collections.abc import Callable, Iterable
def top[T](items: Iterable[T], score: Callable[[T], float]) -> T:
best: T | None = None
best_score = float("-inf")
for item in items:
value = score(item)
if best is None or value > best_score:
best, best_score = item, value
if best is None:
raise ValueError("top() of an empty iterable")
return bestT ties the input element type to the return type, so top(orders, lambda o: o.total) returns an Order, not Any. Accepting Iterable[T] lets callers pass lists, sets or generators. The T | None local plus the explicit empty check keeps the function honest under --strict.
StaffHow would you introduce static typing into a 300,000-line untyped Python codebase without stopping feature work?
Add a checker to CI immediately in a lenient configuration that checks only annotated functions, so it produces signal without blocking anyone. Require hints on all new and changed functions through code review or a lint rule. Type the most-used boundaries first, such as service interfaces, repository methods and API handlers, because every caller benefits. Turn on stricter settings per package as each one becomes clean, and never relax a package once it is strict. Use Protocol at seams to avoid tangled imports, TYPE_CHECKING for type-only imports, and track the count of Any and type: ignore comments as a metric that only goes down. Pair it with Pydantic at external boundaries, because static types say nothing about incoming JSON.
Next: you now know how Python code is structured, typed and organised. The next three pages are about what happens when it runs for real: 3.13.13 explains how CPython manages memory, how its garbage collector works, and the Global Interpreter Lock that shapes all Python concurrency.