Python Type Hints: A Practical Guide
How to actually use Python type hints beyond the basics — generics, Optional, Protocol, and when they’re worth the effort
Type hints are optional in Python, which means a lot of developers skip them entirely or use them inconsistently. Here’s what’s actually worth adopting, and why. The examples were checked with mypy 2.4.1 on Python 3.14 and 3.15.
The basics, quickly
def greet(name: str, times: int = 1) -> str:
return f"Hello, {name}! " * times
print(greet(42)) # runs fine: Hello, 42!Type hints don’t affect runtime behaviour on their own: Python doesn’t enforce them, and greet(42) above runs without complaint even though 42 isn’t a str. Their value comes from tooling. Your editor’s autocomplete gets much better, and a type checker like mypy catches the mismatch before you run the code: on this file it reports Argument 1 to "greet" has incompatible type "int"; expected "str". Newer checkers such as Pyright, Meta’s Pyrefly and Astral’s ty do the same job, usually faster.
Optional and Union: handling “might be None”
from typing import Optional
def find_user(user_id: int) -> Optional[dict]:
# returns None if not found
...Optional[dict] is shorthand for dict | None. In modern Python (3.10+), the pipe syntax is preferred and clearer:
def find_user(user_id: int) -> dict | None:
...This matters more than it looks — a function that can return None but isn’t typed that way is a common source of AttributeError crashes when a caller forgets to check.
Generics: typing containers properly
def get_first(items: list[str]) -> str | None:
return items[0] if items else NoneModern Python lets you use built-in generics directly (list[str], dict[str, int]) rather than importing List/Dict from typing: cleaner, and it’s been the recommended approach since Python 3.9.
When a function should work for any element type and keep that type in its result, Python 3.12 added a shorter syntax for type parameters (PEP 695) that replaces TypeVar:
def first[T](items: list[T]) -> T | None:
return items[0] if items else None
print(first([1, 2, 3])) # 1, and a checker infers int | None
print(first(["a"])) # a, and a checker infers str | NoneWithout a type parameter you’d have to choose list[str] or lose the connection between the input and output types. This syntax needs Python 3.12 or later; older code uses TypeVar from typing.
Protocol: structural typing without inheritance
from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None: ...
def render(shape: Drawable) -> None:
shape.draw()Protocol lets you type-hint “anything with a draw() method” without requiring a class to explicitly inherit from a base class — this is Python’s version of structural typing (duck typing, but checkable). Useful when you’re typing code that works with objects from libraries you don’t control, where forcing inheritance isn’t an option.
TypedDict: typing dictionaries with a known shape
from typing import TypedDict
class UserData(TypedDict):
name: str
age: int
def process(user: UserData) -> None:
print(user["name"])If you’re passing around dictionaries with a consistent, known set of keys (common with JSON API responses before you’ve modeled them as proper classes), TypedDict gives you the type-checking benefit without the overhead of defining a full class.
Forward references: what changed in Python 3.14
Annotations used to be evaluated the moment a function or class was defined, so a method that mentioned its own class needed quotes (-> "Node | None") or from __future__ import annotations. Python 3.14 evaluates annotations lazily (PEP 649 and PEP 749), so this works unquoted:
class Node:
def next(self) -> Node | None:
return NoneOn Python 3.13 the same code raises NameError: name 'Node' is not defined when the class body runs. If you support Python 3.13 or earlier, keep the quotes or the __future__ import. Python 3.15 adds more typing features, including typed extra items for TypedDict (PEP 728) and TypeForm for annotating type expressions (PEP 747).
Where Pydantic fits in
Pydantic goes beyond static type hints — it validates types at runtime, raising real errors when data doesn’t match the declared shape, which plain type hints (checked only by mypy, not enforced by Python itself) don’t do. This is why Pydantic is the standard choice for API request/response models in FastAPI — you need actual runtime validation of untrusted external input, not just editor hints.
Is it worth the effort?
For anything beyond a short script: yes. Type hints pay off fastest on functions other people (or future you) will call without re-reading the implementation — public APIs, shared utility functions, anything with non-obvious inputs. For truly throwaway scripts, skip them; the value comes from code that gets read and called more than once.
Frequently Asked Questions
Do Python type hints do anything at runtime?
Not on their own. Python doesn’t enforce them, so a call with the wrong types still runs. Their value comes from tooling: your editor’s autocomplete gets much better, and a type checker (mypy, Pyright, Pyrefly, ty) can catch mismatches before you run the code.
What’s the difference between type hints and Pydantic?
Type hints are checked only by static tools like mypy and aren’t enforced by Python itself. Pydantic validates types at runtime, raising real errors when data doesn’t match the declared shape — which is why it’s the standard choice for API request/response models handling untrusted external input, like in FastAPI.
Is it worth adding type hints to a small script?
For a genuinely throwaway script, no — skip them. For anything beyond that, yes: type hints pay off fastest on functions other people (or future you) will call without re-reading the implementation, like public APIs and shared utility functions.