Python Typing: A Practical Guide to Type Hints
A practical guide to Python type hints: runtime behavior, built-in generics, Protocol, type aliases, and choosing an annotation style.

Python typing, defined in PEP 484, is a system of annotations attached to function signatures and variable declarations. The critical thing to understand is that these annotations are not enforced by the interpreter. When you write:
def process_order(order_id: int) -> str:
return f"Order {order_id}"The : int and -> str are stored in the function's __annotations__ attribute, but nothing validates that order_id is actually an integer when the function is called. Passing a string works fine at runtime. Type checking happens in a separate step, typically through a static analysis tool like mypy, pyright, or pyre, usually integrated into your editor or CI pipeline.
This separation is the most important mental model for working with Python typing. The annotations serve as documentation and as input to static checkers, not as runtime guards. If you need runtime validation, you need a separate mechanism such as Pydantic or manual checks.
Core Annotation Syntax
Function annotations come in two places: parameter types and return types.
def calculate_total(items: list[float], discount: float = 0.0) -> float:
return sum(items) * (1 - discount)Variable annotations are also supported:
user_id: int = 42
cache: dict[str, bytes] = {}The variable annotation syntax is most useful when the type cannot be inferred from the initial assignment, or when you want to declare a variable that will be assigned later:
result: float | None = NoneFor local variables where the type is obvious from the assignment, annotations add noise without adding information. Reserve them for cases where inference is ambiguous or where the type changes across branches.
Built-in Generics Versus the typing Module
Python 3.9 made built-in collections usable as generic types. Before that, you had to import from typing:
# Python 3.8 and earlier
from typing import Dict, List, Optional
def find_users(ids: List[int]) -> Optional[Dict[str, str]]:
...The | union syntax in annotations requires Python 3.10. If you target Python 3.10 or newer, you can write:
# Python 3.10+
def find_users(ids: list[int]) -> dict[str, str] | None:
...If you are on Python 3.9, use built-in generics with Optional for nullable types:
# Python 3.9
from typing import Optional
def find_users(ids: list[int]) -> Optional[dict[str, str]]:
...The modern syntax is shorter, reads more naturally, and avoids import overhead. The typing module still provides Optional, Union, Literal, Callable, Any, TypeVar, and similar names for older Python versions and for constructs without a built-in syntax. On Python 3.10+, prefer X | None and X | Y over Optional[X] and Union[X, Y].
Note that Optional[X] and X | None are equivalent.
| Syntax | Minimum Python | Example |
|---|---|---|
typing module generics | 3.5 | List[int] |
| Built-in generics | 3.9 | list[int] |
| union syntax | 3.10 | str | None |
type statement | 3.12 | type Alias = ... |
Type Aliases and NewType
A type alias gives a meaningful name to a complex type:
UserId = int
Coordinates = tuple[float, float]
def distance(a: Coordinates, b: Coordinates) -> float:
...Python 3.12 added the type statement, which makes aliases more explicit:
type Coordinates = tuple[float, float]NewType creates a distinct type that is treated as a different type by the static checker but is identical to the underlying type at runtime:
from typing import NewType
UserId = NewType("UserId", int)
def get_user(user_id: UserId) -> User:
...The static checker will reject passing a plain int where a UserId is expected, even though UserId(42) and 42 are the same object at runtime. This is useful for preventing unit confusion or mixing IDs from different domains.
Protocol for Structural Typing
Protocol (PEP 544) lets you define a structural type: a set of attributes or methods that an object must have, without requiring it to inherit from a specific class.
from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None: ...
class Circle:
def draw(self) -> None:
print("drawing circle")
def render(obj: Drawable) -> None:
obj.draw()
render(Circle()) # valid: Circle has a draw methodThis is closer to Go's interface style than to nominal typing. It is useful when you want to accept any object that satisfies an interface, even if it does not inherit from a common base class. The ... in the Protocol body is an ellipsis literal used as a placeholder for the method body.
Runtime Overhead of Type Annotations
Type annotations themselves have negligible runtime cost. Normally, function annotations are evaluated when the function is defined, stored in __annotations__, and then ignored. The main runtime cost appears when annotation expressions reference types from modules that are expensive to import. from __future__ import annotations avoids evaluating annotation expressions by storing them as strings, so imports needed only for annotations can be skipped at runtime. The trade-off is that evaluated annotation objects are not available in __annotations__.
One practical concern: if your annotations import heavy modules just to reference a type, that import cost is paid at module load time. Using string annotations or TYPE_CHECKING guards can avoid this:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from database import Database
def connect(db: "Database") -> None:
...TYPE_CHECKING is True only when a static checker is analyzing the code, so the Database import never executes at runtime. The string annotation "Database" is resolved by the static checker.
Choosing the Right Annotation Style
The decision between Optional[X] and X | None depends on your minimum Python version and whether you use postponed annotations. The decision between typing.List and list depends on whether you support Python 3.8. The decision between Protocol and an abstract base class depends on whether you control the classes being passed in.
For a new codebase targeting Python 3.10+, use the | union syntax and built-in generics. Reserve typing imports for Literal, Callable, TypeVar, Protocol, and similar constructs that have no built-in equivalent. Keep annotations readable: if a type expression becomes too long, extract a type alias rather than repeating it across function signatures.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.