Skip to content

Python Type Hints: Annotations for Better Code

  • How to annotate variables and function parameters and return types.
  • How to express optional values with Optional and the X | None shorthand, and when each is available.
  • How to spell container types with generics such as list[str] and dict[str, int].
  • Where type hints come from: the typing module and the built-in generic syntax added in Python 3.9.
  • Why type hints are worth writing even though Python ignores them at runtime.
  • How mypy and Pyright use hints to catch bugs, and what the runtime impact really is.

Python is dynamically typed, but type hints, introduced in PEP 484, let you annotate variables and functions for better tooling, readability, and static analysis. The annotations are plain Python objects stored on the function, so the interpreter does not enforce them, but external checkers like mypy and Pyright do. This tutorial shows the syntax you will use every day, every example runnable on Python 3.9 or later, with a verification step after each one.

  • Python 3.9 or later. Run python --version to confirm. Some shorthand syntax shown here requires 3.10 or later and is labeled accordingly.
  • Save examples as hints_demo.py and run python hints_demo.py. To actually check the types, install mypy with pip install mypy and run mypy hints_demo.py.
  • Read Variables and Data Types first; type hints name the types that page introduces.

A note on versions: the built-in generic syntax list[str] arrived in Python 3.9, replacing the older typing.List[str] form. The X | Y union syntax arrived in Python 3.10. The runnable samples here use the 3.9-safe forms and label the 3.10+ shorthand where it appears, so the code runs on every supported version.

A variable annotation uses a colon and a type. The annotation is optional and does not bind a value; it merely records the intended type and is checked by a tool, not the interpreter.

customer: str = "Acme"
total: float = 42.5
active: bool = True
# an annotation without a value is legal (no binding happens)
order_id: int
print(customer, total, active)
# Acme 42.5 True

At runtime, the annotation on a module-level variable is stored in __annotations__, but Python does nothing else with it. The value’s type is still dynamic. The annotation is a contract you write for your tools and your readers.

Verify: run print(__annotations__) at the end of the file. It shows the types you recorded. Then assign customer = 123 and confirm Python lets it through, proving hints are not enforced at runtime.

Step 2 — Annotate function parameters and return types

Section titled “Step 2 — Annotate function parameters and return types”

Function annotations are where hints earn their keep. Each parameter gets a type after a colon, and the return type follows an arrow. A checker uses the full signature to flag mismatches.

def format_order(order_id: int, customer: str, amount: float) -> str:
return f"#{order_id} | {customer} | ${amount:.2f}"
print(format_order(1023, "Acme", 42.5))
# #1023 | Acme | $42.50

This signature says the function takes an int, a str, and a float, and returns a str. Mypy will reject format_order("1023", "Acme", 42.5) because the first argument is a string, not an int.

Verify: call the function with format_order("1023", "Acme", 42.5) and confirm Python runs it, returning #1023 | Acme | $42.50. The hint did not stop the call. Run mypy hints_demo.py on a version with the bad call to see the static error instead.

Step 3 — Express optional values with Optional

Section titled “Step 3 — Express optional values with Optional”

Optional values appear constantly: a customer might not have a shipping address yet. Optional[X] means the value is either X or None, which is the same as Union[X, None].

from typing import Optional
def set_discount(customer_id: int, code: Optional[str]) -> str:
if code is None:
return f"{customer_id}: no discount"
return f"{customer_id}: discount {code}"
print(set_discount(1023, "SAVE10"))
# 1023: discount SAVE10
print(set_discount(1024, None))
# 1024: no discount

The idiomatic guard is if code is None, not if not code, because an empty string is a valid discount code and not code would treat it the same as None. The is None check is what the type system expects.

Verify: the sample runs on Python 3.9 and later. For Python 3.10+, the shorthand code: str | None is equivalent and shorter; Optional and the pipe form mean the same thing.

Step 4 — Union types for values that can be more than one type

Section titled “Step 4 — Union types for values that can be more than one type”

When a value can be one of several types, none of them None, use Union. On Python 3.10 and later you can write int | str instead, which reads more clearly.

import sys
from typing import Union
# Union works on every supported version
def normalize_id(value: Union[int, str]) -> int:
return int(value)
# the pipe shorthand requires Python 3.10+
if sys.version_info >= (3, 10):
def normalize_id_pipe(value: int | str) -> int:
return int(value)
print(normalize_id(1023), normalize_id("1024"))
# 1023 1024

The if sys.version_info guard keeps the file runnable on 3.9, since the pipe syntax is a syntax error on older interpreters. In a project that targets only 3.10+, you would drop the guard and use the pipe form directly.

Verify: run the file on Python 3.10 or later and confirm both definitions work. On 3.9 only the Union form is available; the guarded block is skipped.

Step 5 — Spell container types with generics

Section titled “Step 5 — Spell container types with generics”

Containers need a parameter for their element type. Since Python 3.9 you can use the built-in types directly: list[str], dict[str, int], tuple[int, str]. Before 3.9 you had to import List, Dict, and Tuple from typing.

def total_amounts(amounts: list[float]) -> float:
return sum(amounts)
def count_by_region(orders: dict[str, int]) -> dict[str, int]:
return dict(sorted(orders.items()))
print(total_amounts([10.0, 20.5, 7.0]))
# 37.5
print(count_by_region({"West": 3, "East": 1}))
# {'East': 1, 'West': 3}

The built-in generic syntax keeps your imports short and matches how you actually write the container. For a fixed-length tuple with known types, write tuple[int, str]; for a variable-length tuple of one type, write tuple[int, ...].

Verify: the sample uses list[float] and dict[str, int], both valid on Python 3.9+. On 3.8 and earlier the same code needs from typing import List, Dict and List[float], which is why the built-in syntax was such a welcome change.

Step 6 — Import what you need from typing

Section titled “Step 6 — Import what you need from typing”

The typing module provides the named forms: Optional, Union, Any, Callable, Iterable, and more. Newer Python versions move some of these to built-ins, so prefer the built-in form where it exists. Use Any sparingly, since it turns off checking for that value.

from typing import Optional, Callable
# a function that takes a callback
def apply_to_orders(orders: list[int], fn: Callable[[int], int]) -> list[int]:
return [fn(o) for o in orders]
print(apply_to_orders([1023, 1024], lambda o: o + 1000))
# [2023, 2024]

Callable[[int], int] describes a function that takes an int and returns an int. This is the hint you reach for whenever a function accepts another function, which is common in callbacks, filters, and event handlers.

Verify: import Callable and confirm the sample runs. Try annotating the callback as Callable[[str], int] and run mypy to see it flag the mismatch when you pass a lambda that takes an int.

This script models an OrdersPortal function that filters orders by status and sums their amounts, with full annotations. It is runnable on Python 3.9 and later and passes mypy --strict.

from typing import Optional
Order = tuple[int, str, float, str] # order_id, customer, amount, status
def select_by_status(
orders: list[Order],
status: Optional[str] = None,
) -> list[Order]:
if status is None:
return list(orders)
return [o for o in orders if o[3] == status]
def total(orders: list[Order]) -> float:
return sum(o[2] for o in orders)
orders: list[Order] = [
(1023, "Acme", 1500.0, "shipped"),
(1024, "Globex", 800.0, "pending"),
(1025, "Initech", 3200.0, "shipped"),
]
shipped = select_by_status(orders, "shipped")
print(f"shipped count: {len(shipped)}")
print(f"shipped total: ${total(shipped):,.2f}")

Expected output:

shipped count: 2
shipped total: $4,700.00

The Optional[str] = None default is the standard way to make a filter optional: pass None to mean “no filter,” pass a string to mean “only this status.” The return type list[Order] documents that the function always returns a new list, never mutating the input.

Real error messages and their fixes, drawn from the mistakes that surface when you start using type hints.

  • TypeError: 'type' object is not subscriptable — you used list[str] on Python 3.8 or earlier. Either upgrade to 3.9+ or import List from typing and use List[str].
  • mypy: error: Unsupported operand types — you mixed types an operation does not allow, such as adding an int and a string. The hint surfaces a real bug; fix the logic rather than silencing it with Any.
  • mypy: error: Item "None" has no attribute — you used an Optional value without narrowing it. Guard with if value is not None: before you use it, so the checker knows the value is present.
  • SyntaxError on int | str — the pipe union syntax requires Python 3.10. On earlier versions use Union[int, str] from typing.
  • Expecting hints to be enforced at runtime. Python stores annotations and ignores them for correctness. A type error is caught by mypy or Pyright, not by running the program.
  • Using Optional[X] when you mean a default. def f(x: Optional[int]) says the value may be None; it does not provide a default. Add = None for the default, and keep the hint for clarity.
  • Writing if not x for an Optional value. That conflates None with empty string, zero, and empty list. Use if x is None or if x is not None so the check matches the type.
  • Overusing Any. Any disables checking, so a single Any can hide a whole class of bugs. Reach for it only at genuine boundaries, and prefer object plus a narrowing check.
  • Annotating everything, including obvious locals. Hint function signatures and class attributes; let the checker infer local variables from their assignments. Over-annotation adds noise without value.
  • Forgetting to run the checker. Hints you never check are documentation at best. Wire mypy or Pyright into your editor and your continuous integration so the hints actually catch bugs.
  • Read the type-hints feature page for advanced forms: Protocol, TypeVar, overloads, and generics.
  • For runtime typing helpers like get_type_hints, see the typing-extensions feature page.
  • Apply hints to data records with dataclasses, which generate annotated __init__ methods from your fields.
  • Combine hints with structural subtyping using protocols.