Python Type Hints, Explained Properly: Annotations, Optional, TypedDict, Protocol, and a Runtime Checker You Build Yourself
Python lets you write price: float and -> float, yet passes a string and the program still runs. This guide uses a fictional bookshop inventory to explain type hints from scratch: Optional and X | Y, generics, TypedDict, Literal, Protocol, TypeVar, get_type_hints, and a hand-rolled runtime checker. Standard library only, Python 3.12.3, every output a real measured run.

Python has a feature that confuses beginners: you can write price: float after a function parameter and -> float after its name, but if you pass a string in, the program runs anyway and nothing stops it. So what are these annotations for? This guide uses a fictional small bookshop inventory program (book titles, prices, and stock are demo data) to explain type hints from the ground up: how to write annotations, when they help, when they do nothing at all, and what to do if you want them to work at runtime too. All the code uses only the Python standard library, was actually run on Python 3.12.3, and every output quoted is a real measured result.
The single most important sentence goes first, and it is the one the official Python documentation for the typing module opens with: "The Python runtime does not enforce function and variable type annotations." Annotations are for third-party tools — type checkers, IDEs, linters — not for the interpreter. Once that sentence sinks in, everything else follows: type hints are a "convention written for people and for tools", not a gate at runtime.
Basic annotations: learning to write them
Annotation syntax is straightforward: write the type after a parameter name with a colon, and write the return type after an arrow. Here is the most basic function in this guide's demo, computing the total price of some books:
def total(price: float, qty: int) -> float:
"""Unit price x quantity, returns the total price."""
return price * qty
print("total(9.9, 3) =", total(9.9, 3))
print("total(59.0, 2) =", total(59.0, 2))
Output:
total(9.9, 3) = 29.700000000000003
total(59.0, 2) = 118.0
Two details are worth pausing on. First, price: float means "this parameter should be a float", and -> float means "this function should return a float" — "should", not "must". Second, total(9.9, 3) gives 29.700000000000003 rather than 29.7; that is a binary floating-point precision artifact and has nothing to do with annotations. If you need money calculated to the cent, use the decimal module instead of float; this guide will not go into that, except to warn you not to mistake that long tail for a wrong annotation.
Variables can be annotated too, with name: type = value, which the containers section below uses. Methods, function parameters, and return values can all be annotated; annotations change nothing about how the program behaves — delete every annotation and the program produces exactly the same results.
The runtime does not check: wrong types still run
This is the most important section in the guide. Pass a string as the unit price to the function above and see what happens:
wrong = total("9.9", 3)
print("total('9.9', 3) =", repr(wrong), "of type", type(wrong).__name__)
Output:
total('9.9', 3) = '9.99.99.9' of type str
"9.9" * 3 is legal Python — a string times an integer repeats it three times. So the function did not raise an error, and it did not return a number; it quietly returned the string '9.99.99.9'. If later code takes that "total price" and keeps calculating with it, the error will surface far away, and the error message will have nothing to do with the real cause. That is the practical cost of "the runtime does not check": the mistake does not stop where it happens; it flows downstream, and the further it flows, the harder it is to trace.
That example also shows where the real value of type hints lies — not at runtime, but before it. A type checker (such as mypy) reading the line total("9.9", 3) will flag it before you ever run the program: "you passed a str here, but the function wants a float". The mistake is caught while you are writing code, not when a customer is checking out. The value of annotations is "moving some runtime errors forward to write time".
Values that may be missing: Optional, Union, and X | Y
The most common type problem in real programs is not "the wrong type was passed" but "the value might not exist". Looking up a book's price: if the book is in the catalog there is a price; if it is not, there is nothing — and the usual way to express "nothing" is to return None. But None and float are two different types, so the annotation has to spell out both possibilities:
from typing import Optional
def find_price(title: str) -> Optional[float]:
catalog = {"Python Basics": 59.0, "Algorithms Illustrated": 79.0}
return catalog.get(title)
print("find_price('Python Basics') =", find_price("Python Basics"))
print("find_price('A Book That Does Not Exist') =", find_price("A Book That Does Not Exist"))
Output:
find_price('Python Basics') = 59.0
find_price('A Book That Does Not Exist') = None
Optional[float] means float | None — this value is either a float or None. Since Python 3.10 there is a shorter spelling: join the possible types with a vertical bar |:
from typing import Union
def discount(price: float, rate: Union[float, None]) -> float:
"""rate of None means no discount; can also be written float | None."""
if rate is None:
return price
return price * rate
print("discount(100.0, 0.8) =", discount(100.0, 0.8))
print("discount(100.0, None) =", discount(100.0, None))
Output:
discount(100.0, 0.8) = 80.0
discount(100.0, None) = 100.0
Union[float, None] and float | None mean the same thing; the second is the recommended spelling from Python 3.10 onward — shorter and easier to read. New code should prefer X | Y; use Optional and Union only when you need compatibility with Python 3.9 or earlier. The real benefit of writing Optional is that it forces you to face the fact that "the value may not exist": a caller who sees a return type of float | None knows it has to check for None before using the value, instead of assuming it is always a number — and many NoneType has no attribute errors come from callers forgetting exactly that.
Generic containers: list[str], dict[str, int]
Saying "this is a list" is not enough; you also need to say "what the list holds". Since Python 3.9, built-in containers can be subscripted directly with their element types:
titles: list[str] = ["Python Basics", "Algorithms Illustrated", "Computer Systems"]
stock: dict[str, int] = {"Python Basics": 12, "Algorithms Illustrated": 5, "Computer Systems": 3}
print("Titles:", titles)
print("Stock:", stock)
print("Total stock =", sum(stock.values()), "copies")
Output:
Titles: ['Python Basics', 'Algorithms Illustrated', 'Computer Systems']
Stock: {'Python Basics': 12, 'Algorithms Illustrated': 5, 'Computer Systems': 3}
Total stock = 20 copies
list[str] means "a list whose elements are all strings"; dict[str, int] means "a dict with string keys and integer values". A type checker that sees stock["Python Basics"] + " copies" will complain immediately — you cannot add an integer and a string — while without the annotation that error would only appear when the program reaches that line. Container annotations have a second benefit: IDE autocompletion. When you type titles[0]., the IDE knows it is a string and suggests string methods; without the annotation it can only guess.
One easily missed point: the list[str] spelling only works from Python 3.9 onward; before that it had to be written as typing.List[str]. In new code, always use the built-in spelling; there is no need to import the capitalized List and Dict from typing any more.
TypedDict: giving a dict a shape
Dicts in Python are too free: any key and any value can go in. The cost of that freedom is that a misspelled key only shows up at runtime. TypedDict pins down a dict's "shape": which keys it has and what type each key holds:
from typing import TypedDict
class Book(TypedDict):
title: str
price: float
stock: int
book: Book = {"title": "Python Basics", "price": 59.0, "stock": 12}
print("book =", book)
print("book['title'] =", book["title"])
try:
print(book["author"])
except KeyError as e:
print("book['author'] raises: KeyError", e)
Output:
book = {'title': 'Python Basics', 'price': 59.0, 'stock': 12}
book['title'] = Python Basics
book['author'] raises: KeyError 'author'
Note the last line: accessing the missing key book["author"] raises a KeyError 'author' at runtime, not a type error. TypedDict only blocks wrong keys at static-check time — a type checker reading book["author"] will say "there is no author key in Book"; at runtime it is just an ordinary dict and raises whatever it would normally raise. So the value of TypedDict is "knowing what is in the dict while you are writing code", not "an extra layer of protection at runtime". It fits best where dicts have a fixed structure with many fields: JSON data, configuration, API responses.
If the shape needs methods, defaults, or stronger constraints, use a dataclass instead of a TypedDict. The division of labor is: TypedDict handles "the shape of a plain data dict", dataclass handles "a data object with behavior". Pick the wrong tool and the code gets awkward fast.
Literal: the value can only be one of these
Some parameters are not about "what type" but "which specific values". A payment method, for example, can only be cash or card — nothing else:
from typing import Literal
def checkout(mode: Literal["cash", "card"]) -> str:
return f"Payment method: {mode}"
print(checkout("cash"))
print("checkout('wechat') =", checkout("wechat"))
Output:
Payment method: cash
checkout('wechat') = Payment method: wechat
checkout("wechat") still runs and returns Payment method: wechat — the Literal constraint applies only at static-check time. A type checker reading that line will complain: "mode can only be 'cash' or 'card'; 'wechat' is not in the list". Literal fits anywhere a value is one of a fixed set of strings or numbers: mode parameters, status fields, configuration options. It is less work than writing if mode not in ("cash", "card"), and the constraint sits in the function signature, where callers can see it at a glance.
Protocol: no inheritance needed, just the method
A common need in Python is a function that accepts "anything with a certain method", regardless of what class it is. Protocol exists for exactly that: it defines a set of method signatures, and any class that implements those methods counts as matching, without explicitly inheriting anything:
from typing import Protocol
class Printable(Protocol):
def display(self) -> str: ...
class BookItem:
def display(self) -> str:
return "Book: Python Basics"
class MagazineItem:
def display(self) -> str:
return "Magazine: The Programmer's Monthly"
def show(item: Printable) -> None:
print(item.display())
show(BookItem())
show(MagazineItem())
Output:
Book: Python Basics
Magazine: The Programmer's Monthly
Neither BookItem nor MagazineItem inherits Printable, but both have a display() method, so both can be passed to show(). This is structural typing: what matters is "what you have", not "whose child you are". The difference from inheritance is: inheritance says "I declare that I am a kind of thing"; a Protocol says "I can do a certain thing". Python is a duck-typing language — "if it walks like a duck and quacks like a duck, it is a duck" — and Protocol is that intuition written into the type system, so checkers can understand it too.

Reading the annotations back: get_type_hints
Annotations do not vanish once written — they live on the function object as a dict, and a program can read them back:
from typing import get_type_hints
print("Annotations of total:", get_type_hints(total))
print("Annotations of discount:", get_type_hints(discount))
Output:
Annotations of total: {'price': <class 'float'>, 'qty': <class 'int'>, 'return': <class 'float'>}
Annotations of discount: {'price': <class 'float'>, 'rate': typing.Optional[float], 'return': <class 'float'>}
Note the second line: discount's rate was written as Union[float, None], but it reads back as typing.Optional[float] — the two are the same thing, Optional[X] is shorthand for Union[X, None], and Python displays it in the Optional form when reading it back. This function is the key to the next section's hand-rolled runtime checker: since annotations can be read out, a piece of code can check the arguments against them before the function runs.
A hand-rolled runtime checker: making annotations work at runtime
As repeated throughout this guide, "the runtime does not check". If you genuinely want wrongly typed calls blocked at runtime too, you can write a decorator yourself: use get_type_hints to read the annotations, use inspect.signature to match actual arguments to parameters, and check each one with isinstance. Below is a simplified demo version — it only does shallow checks and does not look inside nested generics (for list[str] it checks "is it a list" but not "is every element a string"), which is enough to show the principle:
import functools
import inspect
def _matches(value, hint) -> bool:
"""Shallow check only: enough for the demo, not a full type checker."""
import types
origin = getattr(hint, "__origin__", None)
if origin is Union or isinstance(hint, types.UnionType):
args = getattr(hint, "__args__", ())
return any(_matches(value, a) for a in args)
if hint is type(None):
return value is None
if origin in (list, dict):
return isinstance(value, origin)
if isinstance(hint, type):
return isinstance(value, hint)
return True
def checked(func):
hints = get_type_hints(func)
sig = inspect.signature(func)
@functools.wraps(func)
def wrapper(*args, **kwargs):
bound = sig.bind(*args, **kwargs)
bound.apply_defaults()
for name, value in bound.arguments.items():
hint = hints.get(name)
if hint is not None and not _matches(value, hint):
raise TypeError(
f"{func.__name__}() argument {name!r} should be {hint}, "
f"got {type(value).__name__} ({value!r})"
)
return func(*args, **kwargs)
return wrapper
@checked
def total_checked(price: float, qty: int) -> float:
return price * qty
print("total_checked(9.9, 3) =", total_checked(9.9, 3))
try:
total_checked("9.9", 3)
except TypeError as e:
print("total_checked('9.9', 3) raises:", e)
Output:
total_checked(9.9, 3) = 29.700000000000003
total_checked('9.9', 3) raises: total_checked() argument 'price' should be <class 'float'>, got str ('9.9')
This time the error stops where it happened, and the message says exactly which argument, what type it should be, and what was actually passed. Here is one more example, with float | None:
@checked
def discount_checked(price: float, rate: float | None) -> float:
if rate is None:
return price
return price * rate
print("discount_checked(100.0, None) =", discount_checked(100.0, None))
try:
discount_checked(100.0, "20% off")
except TypeError as e:
print("discount_checked(100.0, '20% off') raises:", e)
Output:
discount_checked(100.0, None) = 100.0
discount_checked(100.0, '20% off') raises: discount_checked() argument 'rate' should be float | None, got str ('20% off')
None passes cleanly, and the string "20% off" is blocked — both possibilities of float | None are handled correctly. Three clear limitations of this teaching version: first, it only does shallow checks, so an integer mixed into a list[str] would slip through; second, it checks arguments but not return values; third, reading annotations and binding arguments on every call costs performance, so it does not belong on a hot path called in a tight loop. In production, if you genuinely need runtime checking, use an established library (such as pydantic or beartype) instead of maintaining your own. Writing one yourself is worthwhile for understanding the principle: type hints can be exploited at runtime precisely because annotations are real data stored on objects, not comments that get thrown away.
Going further: TypeVar, one function for any type
In the examples so far, every function handles a fixed type. But sometimes one function has to handle "any type" — taking the first element of a list, for example, where the list can hold anything and the return is that same type. That is what the type variable TypeVar is for:
from typing import TypeVar
T = TypeVar("T")
def first(items: list[T]) -> T | None:
"""Take the first element of a list; return None for an empty list."""
return items[0] if items else None
print("first(['a', 'b']) =", first(["a", "b"]))
print("first([1, 2, 3]) =", first([1, 2, 3]))
print("first([]) =", first([]))
Output:
first(['a', 'b']) = a
first([1, 2, 3]) = 1
first([]) = None
T is a placeholder: pass a list[str] and T becomes str, so the return is a str; pass a list[int] and T becomes int, so the return is an int. The type checker can infer the return type from the argument type, and callers get correct IDE completions on the result. Without TypeVar, this function's return could only be annotated as Any (any type), and callers would lose all type information. Python 3.12 added a shorter spelling for generic functions — def first[T](items: list[T]) -> T | None:, with the type parameter right after the function name; the two spellings are equivalent, and new code can use the new one while TypeVar is the safer choice for older projects.
The five mistakes beginners make most
The first mistake is believing annotations are checked. This guide has said it three times already, so once more: price: float does not guarantee that price is a float. Treating annotations as validation is the single most common source of type-related bugs.
The second mistake is writing Optional and then forgetting to check for None. A function returns float | None, the caller does arithmetic on the result directly, and as soon as a None shows up in the data the program raises a TypeError. The correct approach is to check first — if price is None: ... — or give a default with or. The point of the annotation is precisely to remind you that "there may be no value here"; seeing the reminder and ignoring it makes the annotation pointless.
The third mistake is annotating only half of a container. Writing list instead of list[str] tells the checker "this is a list, and I don't know what is in it" — so the checker cannot check the element types either. Write containers out in full: dict becomes dict[str, int], and tuple becomes tuple[int, str] (each position in a tuple can have a different type, unlike a list).
The fourth mistake is using a mutable object as a default value in a function definition. Writing def add_book(title: str, tags: list[str] = []) creates that empty list once, and every call shares the same one — an old Python trap that has nothing to do with annotations, except that the annotation makes it look more "official" and therefore easier to overlook. Use None as the default and check inside the function: def add_book(title: str, tags: list[str] | None = None), then if tags is None: tags = [].
The fifth mistake is forward references. When a function needs to refer to a class that has not been defined yet — for example, a method of class Node that returns a Node — writing the annotation plainly raises a NameError because Node does not exist yet. The fix is to write the annotation as a string, "Node", or to add from __future__ import annotations at the top of the file, which makes all annotations strings evaluated lazily. The second approach is cleaner, and new files can include it from the start.
Making annotations a habit: a minimal workflow
Once you know how to write annotations, the next step is turning them into a habit rather than something you remember only occasionally. Here is a minimal three-step workflow. First, write the annotation when you write the function: what types the parameters are, what type it returns — write them together with the signature, not afterwards, because annotations added later are the ones most likely to disagree with the actual code. Second, install a type checker in your project (mypy is the most common) and run mypy . before committing, clearing the errors before the code goes in; at first, check only new files and expand the coverage gradually — demanding zero errors across the whole project on day one is a good way to make everyone give up. Third, put type checking in continuous integration: run the check automatically on every commit and block merges when it fails — that is how annotations stay trustworthy instead of slowly rotting into decoration nobody believes. None of these three steps changes any code logic, the cost is low, and the payoff is real: many "wrong argument passed" bugs that used to appear only when the program ran get caught before the code is committed. Once that flow is running smoothly, consider a stricter mode (such as mypy's --strict), or gradually annotating older code — strict first, then loose; new code first, then old code. That order is the least likely to be abandoned halfway.
When to annotate, and when not to
Finally, a few practical rules. First, annotate public interfaces first: if a function will be called by many people, or imported by other modules, its parameter and return types are worth writing down — the annotation is the function's "instruction manual", letting callers know what to pass without reading the implementation. Second, complex data structures are worth annotating: a dict inside a dict, a list of tuples — writing dict[str, list[Book]] is more precise than three lines of comments and easier to maintain. Third, throwaway scripts for yourself can skip them: a one-off file-processing script or an experiment gains less from annotations than they cost to write, so skipping them is reasonable. Fourth, do not annotate for the sake of annotating: if an annotation is harder to read than the code itself, the type itself probably needs simplifying — simplify the code first, then add the annotation.
One more trap to avoid: do not treat annotations as validation. Seeing price: float and assuming the incoming price is definitely a float is the most common beginner misunderstanding. An annotation is an "expectation", not a "guarantee"; a guarantee needs one of two things: a type checker before running (such as mypy, which scans a whole project for type errors from the command line), or an active check at runtime (such as the decorator hand-written in this guide, or a library like pydantic). Most projects only need the first one. The complete workflow for type hints is: write annotations, run the checker before committing, and let the runtime do what it does. Once that loop is running smoothly, type hints are genuinely in use.
Comments (0)
Sources
Related articles
Adding a book parses to price=59.9, count=3, total 179.7; listing by price takes 2; four errors all exit with code 2; --pri abbreviates, and no subcommand parses to None. Python 3.12.3 stdlib, measured.
Port 8000 in code, 8080 in the config file, 9090 from the environment: each layer changes only its own keys, and the last one wins. Defaults plus INI plus env vars, bool('False') is True, and a missing key should fail at startup. Python 3.12.3 stdlib only.
tmux 3.4, zero packages: 1 session, 2 windows, 3 panes; the logs window prints 1 to 5, editor panes report ready. Detach with Ctrl-b d, reattach with tmux attach — the session outlives the connection. Mouse, prefix key and history limit in ~/.tmux.conf included.