Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Standard Library: Data Structures and Functional Tools

The typing module

Reference for Python's typing module: Optional, Union, Literal, TypedDict, Protocol, TypeVar, Callable, Self, cast and how hints behave at runtime.

The typing module holds the vocabulary of Python's type hints: names for "a list of strings", "an optional integer", "a function taking an int and returning a string", structural interfaces and more. Hints document your code and let tools such as mypy, pyright and your editor find bugs before you run anything.

Python itself does not enforce hints. A function annotated -> int can return a string and nothing happens at runtime. Since Python 3.9 you can use the built-in generics (list[int], dict[str, int]) directly, and since 3.10 you can write unions as int | None. That means many older typing names (List, Dict, Optional, Union) are no longer needed in new code.

Python
def first(items: list[str]) -> str | None:
    return items[0] if items else None

Try it

Python Hints are just data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python TypedDict, Protocol, NamedTuple and cast

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common names

Name Meaning
Any Opts out of checking for that value.
Optional[X] X or None; the same as X | None.
Union[X, Y] Either type; the same as X | Y.
Literal["a", "b"] Only these exact values.
Final, ClassVar A name that must not be rebound; an attribute that belongs to the class.
Callable[[A, B], R] A callable taking A and B and returning R. Prefer collections.abc.Callable.
TypeVar, Generic, ParamSpec Building blocks for generic functions and classes. On 3.12+ use def f[T](...) and class Box[T]:.
Protocol Structural interface: any object with the right methods matches, no inheritance needed.
TypedDict A dictionary with a fixed set of string keys and typed values.
NamedTuple A tuple subclass with named, typed fields.
Self The type of the current instance or class (3.11).
TypeAlias, type X = ... Names a type; the type statement is available from 3.12.
overload Declares several call signatures for one function.
cast(T, value) Tells the checker the value is T; does nothing at runtime.
TYPE_CHECKING False at runtime, True for type checkers; guards imports used only in hints.
get_type_hints(), get_origin(), get_args() Inspect annotations at runtime.
Annotated[T, meta] Attaches extra metadata to a type.
NoReturn, Never A function that never returns normally.

Return value of get_type_hints(obj): a dictionary of the evaluated annotations, with string (forward) references resolved.

Raises: NameError from get_type_hints() if a forward reference cannot be resolved.

Usage notes

  • Hints are not validation. For runtime checks use isinstance(), a validation library, or dataclass __post_init__ code.
  • Prefer built-in generics. list[int], dict[str, int], tuple[int, ...], type[Cls] need no import (3.9+). typing.List and friends are deprecated aliases that still work.
  • Prefer X | None over Optional[X] on 3.10+. Optional means "may be None", not "argument may be omitted"; a default value is what makes an argument optional.
  • Use abstract types for parameters (Sequence, Mapping, Iterable from collections.abc) and concrete types for return values.
  • Forward references. A class cannot name itself in an annotation evaluated at definition time on older versions; use a string ("Node") or from __future__ import annotations. Python 3.14 evaluates annotations lazily, so this is rarely needed on new versions.
  • Protocol classes only need @runtime_checkable for isinstance(), and then only method presence is checked, not signatures.
  • TypedDict instances are ordinary dictionaries at runtime; type(m) is dict.
  • cast() and # type: ignore silence the checker; they do not make wrong code right.
  • Type checkers are separate tools. Install and run mypy or pyright yourself; they are not part of the standard library.