Skip to content
Happy Programming Guide
Start learning
Python

Python Type Hints Explained With Examples

Type hints document what a function expects and let a checker find bugs before the code runs. The syntax for every common case, how to run a checker, and where hints are not worth it.

Keys of a mechanical keyboard seen up close

Type hints are annotations that say what type a variable, parameter or return value is meant to be. Python does not enforce them at runtime; they are documentation that tools can read. An editor uses them for autocomplete, and a checker such as mypy or Pyright uses them to find mistakes — a function called with a string where it expects a list, a value that might be None used as if it never is — before anything runs. This article gives the syntax for every case you will meet and shows the checker catching a real bug.

The basics#

Python
def greet(name: str, times: int = 1) -> str:
    return ("Hello, " + name + "! ") * times

count: int = 0
price: float = 9.99
active: bool = True

A colon after a parameter or variable name, an arrow before the return type. The hints do nothing when the code runs; greet(42) still executes and fails inside. What changes is that the editor now underlines greet(42) as you type it, and a checker reports it.

Collections#

Python
def total(prices: list[float]) -> float:
    return sum(prices)

def index_by_id(users: list[dict[str, str]]) -> dict[str, dict[str, str]]:
    return {u["id"]: u for u in users}

def coords() -> tuple[float, float]:        # exactly two floats
    return 51.5, -0.1

def tags() -> set[str]:
    return {"python", "types"}

Since Python 3.9 the built-in types take subscripts directly; the older from typing import List, Dict forms still work but are no longer needed. Use Sequence[str] or Iterable[str] from collections.abc for parameters when you only read from the collection; it lets callers pass a tuple or a generator, not just a list.

Optional and union#

Python
def find_user(user_id: int) -> User | None:      # may return None
    ...

def parse(value: int | str) -> int:              # accepts either
    return int(value)

user = find_user(7)
print(user.name)             # checker: "name" is not a known attribute of "None"

if user is not None:
    print(user.name)         # fine: narrowed

The X | None form, from Python 3.10, replaces Optional[X]. Catching the second example — using a possibly-None value without checking — is the single most valuable thing a checker does; it is the NoneType errors of a codebase found before they happen.

Functions as values#

Python
from collections.abc import Callable

def apply(items: list[int], fn: Callable[[int], int]) -> list[int]:
    return [fn(x) for x in items]

apply([1, 2, 3], lambda x: x * 2)
apply([1, 2, 3], str)        # checker: incompatible return type

Callable[[argument types], return type]. For anything more complex, a Protocol describes the required signature by example.

Dictionaries with known keys#

Python
from typing import TypedDict, NotRequired

class Config(TypedDict):
    host: str
    port: int
    debug: NotRequired[bool]

cfg: Config = {"host": "localhost", "port": 8080}
cfg["prot"]                  # checker: "prot" is not a defined key

JSON-shaped data with fixed keys gets a TypedDict. For anything with behaviour, a dataclass is usually better, and its fields are type hints already.

A fixed set of values#

Python
from typing import Literal

def open_file(path: str, mode: Literal["r", "w", "a"]) -> None: ...

open_file("x.txt", "rw")     # checker: not one of the allowed literals

Generics#

Python
def first[T](items: list[T]) -> T:          # Python 3.12 syntax
    return items[0]

first([1, 2, 3])             # int
first(["a", "b"])            # str

The function works for any element type and the checker tracks which. Before 3.12, the same thing used TypeVar; the new bracket syntax replaces it. Generic classes work the same way: class Stack[T]:.

Running a checker#

Terminal
pip install mypy
mypy app.py

# or Pyright, which is what VS Code's Pylance uses
pip install pyright
pyright app.py
Output
app.py:14: error: Item "None" of "User | None" has no attribute "name"  [union-attr]
app.py:21: error: Argument 1 to "total" has incompatible type "list[str]"; expected "list[float]"  [arg-type]
Found 2 errors in 1 file

In VS Code, Pylance shows the same errors inline as you type once python.analysis.typeCheckingMode is set to basic or standard. Add the checker to CI so a type error fails the build the way a test failure does.

How much to annotate#

Function signatures: always, in any code that will be read by someone else or by you next month. That is where hints pay for themselves, because a signature is the contract. Local variables: rarely; the checker infers them from the assignment, and x: int = 5 adds nothing. Return types: yes, because they catch the missing return and the accidental None. Start with signatures and stop there until you have a reason to go further.

Where they are not worth it: throwaway scripts, code that manipulates deeply dynamic data where the true type is “whatever the API sends”, and the interiors of small private helpers where the types are obvious from three lines of context.

Escape hatches#

Python
from typing import Any, cast

def load(raw: Any) -> None: ...             # Any: accepts anything, checks nothing

value = cast(int, some_untyped_call())      # cast: tell the checker, without runtime effect

result = risky()  # type: ignore[attr-defined]

Each turns off checking for one spot. Use them at boundaries with untyped code, and treat every one as a small debt to repay when the boundary gets types.

Questions people ask#

Do type hints slow the code down?

No. They are stored as metadata and ignored by the interpreter. Since 3.14, annotations are not even evaluated until something asks for them.

Which checker, mypy or Pyright?

Both are good. Pyright is faster and is what VS Code uses; mypy has a longer history and more plugins. Pick one per project and configure it in pyproject.toml.

What is from __future__ import annotations?

It made annotations lazy strings on older Pythons, allowing forward references and the X | None syntax on 3.7 to 3.9. On current versions it is rarely needed.

Can I add types to a big untyped codebase?

Gradually. Annotate the modules you touch, run the checker on those files only, and expand. Both checkers support per-module strictness for exactly this.

Where to go next#

Python dataclasses explained with examplesRead next

Keep reading

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *