Skip to content

Lesson 28 of 52Pythonic Python

Type Hints

Annotate Python code with modern type hints, catch bugs with mypy or pyright, and know what hints do not do.

21 min read0/7 questions

Open any modern Python codebase, FastAPI app or library and you will see def get_user(user_id: int) -> User | None:. Type hints document what a function expects and returns, let your editor autocomplete and flag mistakes as you type, and let tools like mypy and pyright catch whole classes of bugs before the code runs. FastAPI and Pydantic even use them to validate requests. Most teams now require them.

Annotating variables and functions

A type hint (or annotation) is written after a colon for parameters and variables, and after -> for a return value.

Python
def greet(name: str, times: int = 1) -> str: return ", ".join([f"hi {name}"] * times) count: int = 0ratio: float = 0.5names: list[str] = ["Ada", "Sam"] print(greet("Leo", 2))print(greet.__annotations__)
Output
Press Run (⌘ Enter) to see what happens.

Hints are stored on the function (__annotations__) but Python itself does nothing else with them. That surprises everyone the first time:

Predict the outputPython

What does this print?

def double(n: int) -> int:
  return n * 2

print(double("ab"))
Need a nudge? Hints walk you through it.
Who actually looks at your type hints
  1. Your editor (Pylance / pyright)red squiggles and autocomplete as you type
  2. Type checker in CI (mypy or pyright)fails the build on type errors
  3. Libraries that read hints (Pydantic, FastAPI)validate and convert data at runtime, on purpose
  4. The Python interpreterstores them in __annotations__ and otherwise ignores them

The real value of hints comes from static tools that read your code without running it.

1/3

Collections, None and unions

Since Python 3.9 you write generic collections with the built-in types and square brackets. Since 3.10, X | Y means "either type".

scores: list[int] = [90, 85]
lookup: dict[str, float] = {"pi": 3.14}
point: tuple[int, int] = (3, 4)            # exactly two ints
history: tuple[str, ...] = ("a", "b")       # any length
unique: set[str] = set()
 
def find(user_id: int) -> str | None:       # may return nothing
    ...
 
def parse(value: int | str) -> int:         # accepts either
    ...

str | None is the modern spelling of Optional[str] from the typing module. You will see both. "Optional" means "may be None", not "the argument is optional".

A checker forces you to handle the None case before using the value. This is called narrowing:

Python
def find_email(users: dict[str, str], name: str) -> str | None: return users.get(name) def domain(users: dict[str, str], name: str) -> str: email = find_email(users, name) if email is None: # narrows str | None to str below return "unknown" return email.split("@")[1] # safe: mypy knows email is a str here people = {"ada": "ada@example.com"}print(domain(people, "ada"), domain(people, "sam"))
Output
Press Run (⌘ Enter) to see what happens.
Quick check
What does def f(x: Optional[int]) mean?
Need a nudge? A hint rules out a wrong answer.

Literal, TypedDict and Callable

The typing module covers more precise shapes:

from typing import Literal, TypedDict
from collections.abc import Callable
 
Mode = Literal["r", "w", "a"]               # only these exact values
def open_log(mode: Mode) -> None: ...
 
class UserDict(TypedDict):                  # a dict with known keys
    id: int
    email: str
    admin: bool
 
def apply(fn: Callable[[int, int], int], a: int, b: int) -> int:
    return fn(a, b)                         # fn takes two ints, returns an int
  • Literal restricts a value to specific constants. Great for modes and status strings.
  • TypedDict describes a dict with fixed keys, such as parsed JSON, where a dataclass would be overkill.
  • Callable[[args], return] describes a function you pass in. Import it from collections.abc.
Match the pairs0/5 matched

Match each hint to what it means.

Choose an item, then its match on the other side.

Functions that return nothing, never return, or yield

Three kinds of function trip people up the first time they annotate them.

Returning nothing. A function that only has side effects returns None, so annotate it -> None. Do not leave the return type off: to mypy an unannotated return means "not checked", not "returns nothing". And avoid functions that return a value on some paths and fall off the end on others. The checker will force every caller to handle None, which is usually the checker telling you the function has two jobs.

Never returning. A function that always raises or exits, like fail(message) that raises an HTTPException, gets -> Never (from typing, 3.11; older code spells it NoReturn). The checker then knows code after the call is unreachable, so narrowing keeps working:

from typing import Never
 
def fail(message: str) -> Never:
    raise ValueError(message)
 
def port(raw: str | None) -> int:
    if raw is None:
        fail("PORT is not set")
    return int(raw)        # the checker knows raw is a str here

Yielding. A generator function does not return its items, it returns a generator object, and the hint describes that object. For the common case, use Iterator[T]: "something you can loop over that produces T". When the generator also receives values with send() or returns a final value, use Generator[YieldType, SendType, ReturnType]. Since Python 3.13 the last two default to None, so Generator[int] is valid too.

Python
from collections.abc import Generator, Iterator def countdown(n: int) -> Iterator[int]: while n > 0: yield n n -= 1 def running_total() -> Generator[int, int, str]: total = 0 while True: value = yield total # receives an int from send() if value < 0: return f"stopped at {total}" total += value print(list(countdown(3)))gen = running_total()next(gen)print(gen.send(5), gen.send(10))try: gen.send(-1)except StopIteration as stop: print(stop.value) # the str return value
Output
Press Run (⌘ Enter) to see what happens.

A @contextmanager function is a generator too, so it is annotated -> Iterator[Connection], where Connection is whatever it yields. Async versions use AsyncIterator[T] and AsyncGenerator[T].

For callbacks, Callable[[Event], None] documents that you ignore the result. If you genuinely accept callbacks that return anything, Callable[[Event], object] says so explicitly.

Generics: TypeVar and the 3.12 syntax

What is the return type of a function that returns the first item of a list? It depends on the list: list[int] gives int, list[str] gives str. A type variable expresses "the same type, whatever it is".

def first[T](items: list[T]) -> T:
    return items[0]
 
class Box[T]:
    def __init__(self, value: T) -> None:
        self.value = value
Python
def first[T](items: list[T]) -> T: return items[0] def pair_up[K, V](keys: list[K], values: list[V]) -> dict[K, V]: return dict(zip(keys, values)) n = first([3, 1, 2]) # a checker infers: ints = first(["b", "a"]) # a checker infers: strprint(n + 1, s.upper())print(pair_up(["a", "b"], [1, 2]))
Output
Press Run (⌘ Enter) to see what happens.

Without the type variable you would write list[object] -> object, and the checker would complain about n + 1. Generics keep the precise type flowing through your function. The new def f[T] syntax (PEP 695) is the one to use in new code.

Type aliases with type

Long types get repeated: dict[str, list[tuple[int, str]]] in five signatures is unreadable and a pain to change. A type alias gives it a name. Since Python 3.12 the type statement is the way to write one:

Python
type UserId = inttype Pair[T] = tuple[T, T]type Json = dict[str, Json] | list[Json] | str | int | float | bool | None def swap[T](p: Pair[T]) -> Pair[T]: return (p[1], p[0]) print(type(UserId).__name__, UserId.__name__, UserId.__value__)print(swap((1, 2)))print(Json.__value__) # evaluated only now, so the self-reference works try: isinstance(5, UserId)except TypeError as e: print("TypeError:", e)
Output
Press Run (⌘ Enter) to see what happens.

What the type statement gives you over the old UserId = int or UserId: TypeAlias = int:

  • It is lazy. The right-hand side is only evaluated when something asks for __value__. That is why Json can refer to itself, and why an alias can mention a class defined further down the file, with no quotes.
  • It can be generic. Pair[T] takes a type parameter, just like def swap[T].
  • It is unambiguous. A plain X = int could be an alias or just a variable that holds a class; checkers have to guess. type X = int can only be an alias.

An alias is just another name for the same type. UserId and int are fully interchangeable, so the checker will happily let you pass an OrderId where a UserId is expected. When you want the checker to keep two kinds of id apart, use NewType, which Typing Patterns for Real Code covers. And because the alias object is not a class, isinstance(x, UserId) raises TypeError: at runtime, check against the real type.

Predict the outputPython

What does this print?

type Celsius = float

def warm(t: Celsius) -> bool:
  return t > 20

print(warm(25), Celsius.__value__)
Need a nudge? Hints walk you through it.

Protocol: typing by shape

You met Protocol in the inheritance lesson. In type hints it says "any object with these methods", which keeps your functions flexible:

from typing import Protocol
 
class SupportsClose(Protocol):
    def close(self) -> None: ...
 
def close_all(things: list[SupportsClose]) -> None:
    for t in things:
        t.close()

Files, sockets and your own classes all fit, with no shared base class needed.

Accept abstract, return concrete

Here is a signature you will see in code review:

def normalise(emails: list[str]) -> list[str]: ...

It works, but it is stricter than it needs to be. The function only loops over emails, so it could just as well take a tuple, a set, a generator or a dict's keys. With list[str] the checker rejects all of those, and callers start writing normalise(list(emails)) everywhere. The rule seniors follow: parameters should ask for the least they need, return types should promise the most you can deliver.

Python
from collections.abc import Iterable def normalise(emails: Iterable[str]) -> list[str]: return sorted({e.strip().lower() for e in emails}) print(normalise(["Ada@X.com ", "sam@x.com"])) # listprint(normalise(("ADA@x.com", "ada@x.com"))) # tupleprint(normalise(line for line in ["b@x.com", "a@x.com"])) # generatorprint(normalise({"z@x.com"})) # set
Output
Press Run (⌘ Enter) to see what happens.
Pick the most general type that does the job
  1. Iterable[T]you only loop over it once
  2. Collection[T]you also need len() or `in`
  3. Sequence[T]you also index or slice, or loop twice
  4. list[T]you mutate it: append, sort in place

Iterable accepts lists, tuples, sets, dict views, files and generators. Use it when you make one pass.

1/4

The same idea applies to dicts: take Mapping[str, int] when you only read, MutableMapping or dict when you write. There is a second, subtler win. Sequence and Mapping are read-only, which lets the checker accept a list[int] where a Sequence[float] is expected. A list[float] parameter would reject it, because the function could append a float to the caller's list of ints. Generics and Protocols in Depth explains this (it is called variance) properly.

Do not over-apply it to returns. Returning Iterable[str] "to stay flexible" means every caller who needs len() must wrap your result in list(). If you want freedom to change the implementation later, Sequence[str] is a reasonable middle ground for a read-only result.

Quick check
def total(prices: ...) -> float only does return sum(prices). Which parameter type is the best choice?
Need a nudge? A hint rules out a wrong answer.

Any, object, or no annotation at all

Three ways to say "I am not being specific" behave very differently:

  • object: any value is accepted, but you can do almost nothing with it until you narrow it with isinstance. Safe.
  • Any: any value is accepted, and you can do anything with it. x.whatever() passes. Checking is switched off for that value and everything derived from it.
  • No annotation: the parameter is treated as Any. Worse, mypy by default does not type-check the body of a function with no annotations at all, so obvious errors inside it are silently skipped. Pyright checks the body but has to guess the parameter types. Adding even one annotation (such as -> None) makes mypy check the whole function.

That last point is why a half-annotated codebase can feel safe when it is not. mypy's --strict mode turns on disallow_untyped_defs so unannotated functions become errors, and check_untyped_defs is a gentler step that at least checks their bodies. Generics and Protocols in Depth goes further into object versus Any and how Any spreads.

Quick check
def describe(value: object) -> str: return value.upper(). What does a type checker say?
Need a nudge? A hint rules out a wrong answer.

Running a type checker

Hints pay off when a tool checks them. The two main ones are mypy (the original) and pyright (fast, and powers VS Code's Pylance). Both run without executing your code:

uv add --dev mypyuv run mypy src/
src/app.py:4: error: Argument 1 to "double" has incompatible type "str"; expected "int"  [arg-type]
Found 1 error in 1 file (checked 3 source files)

Start with hints on function signatures (parameters and returns); checkers infer most local variables. Turn on strict = true in your config once a project is fully annotated. And remember that hints describe your own code. Data from outside (JSON, forms, env vars) still needs runtime validation, which is exactly what Pydantic adds.

Quick check
You add hints and run mypy. Which statement is true?
Need a nudge? A hint rules out a wrong answer.
ChallengeEasy

A generic group_by

Write a generic function group_by(items, key) that groups items by the result of calling key(item).

  • Return a dict mapping each key to the list of items with that key, in their original order.
  • Keys appear in the order they are first seen.
  • Annotate it with type variables using the Python 3.12 syntax: def group_by[T, K](items: list[T], key: Callable[[T], K]) -> dict[K, list[T]].
group_by(["apple", "avocado", "banana"], lambda w: w[0])
# {"a": ["apple", "avocado"], "b": ["banana"]}
 
group_by([1, 2, 3, 4], lambda n: n % 2 == 0)
# {False: [1, 3], True: [2, 4]}
Python
from collections.abc import Callable def group_by[T, K](items: list[T], key: Callable[[T], K]) -> dict[K, list[T]]: pass
ChallengeMedium

Validate at the boundary

Type hints are not checked at runtime, so data from outside (like parsed JSON) must be validated by hand (or by Pydantic). Write validate_user(raw) that turns an untrusted dict into a User (a TypedDict with keys id: int, email: str, admin: bool).

Rules:

  • id is required and must be an int. Note that True is technically an int in Python; reject booleans.
  • email is required and must be a str containing "@".
  • admin is optional, defaults to False, and must be a bool if present.
  • Unknown keys are dropped.
  • Raise TypeError for a missing key or wrong type, and ValueError for an email without "@".
validate_user({"id": 7, "email": "ada@example.com", "extra": 1})
# {"id": 7, "email": "ada@example.com", "admin": False}
 
validate_user({"id": "7", "email": "a@b.c"})   # TypeError
validate_user({"id": 7, "email": "nope"})      # ValueError
Python
from typing import Any, TypedDict class User(TypedDict): id: int email: str admin: bool def validate_user(raw: dict[str, Any]) -> User: pass
Key terms
type hint
An annotation like x: int or -> str that documents a type for tools. Not enforced at runtime.
X | None
A union meaning the value may be None; identical to Optional[X].
narrowing
A checker learns a more specific type after a check like if x is None: return.
TypedDict
Describes a dict with a fixed set of keys and value types.
type variable
A placeholder type (T) that links input and output types, written def f[T](...) in 3.12+.
mypy / pyright
Static type checkers that read hints and report type errors without running code.