On this page
typing
Prev: types | Up: stdlib_module | Next: unicodedata
Rel: annotationlib, pydoc, pydoc_data, doctest, unittest
Ref: docs.python.org — typing
Tags: #public #python3 #stdlib
Import
import typing
Overview
Gradual static typing primitives (Protocol, TypedDict, Literal, Final, TypeVar, ParamSpec, Annotated, overload, cast) checked by tools like mypy and pyright. In Python 3.10+, prefer built-in generic syntax (list[str], dict[str, int], int | None) and collections.abc (Callable, Iterable, Mapping, Sequence) over legacy typing.List/Optional/Dict aliases.
Quick Start
from collections.abc import Iterable
from typing import Literal, Protocol
class Summarizable(Protocol):
def summary(self) -> str: ...
def join_summaries(items: Iterable[Summarizable], sep: Literal[", ", "\n"] = ", ") -> str:
return sep.join(item.summary() for item in items)
Implementation Walkthrough
1. Structural Subtyping with Protocol & TypedDict
Protocol lets you type-check by behavior (duck typing) without forcing inheritance; TypedDict types structured JSON-like dictionaries:
from typing import NotRequired, TypedDict
class UserPayload(TypedDict):
id: int
name: str
email: NotRequired[str]
def display_name(user: UserPayload) -> str:
return user.get("email", user["name"])
2. Preserving Signatures on Decorators with ParamSpec (or PEP 695)
from collections.abc import Callable
from functools import wraps
def logged[**P, R](fn: Callable[P, R]) -> Callable[P, R]:
@wraps(fn)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
return fn(*args, **kwargs)
return wrapper
Gotchas & Boundaries
- Annotations are not enforced at runtime:
def f(x: int)will happily accept"hello"unless you validate explicitly or run a static type checker. - Prefer
collections.abcfor parameter types: AcceptSequence[str]orMapping[str, int]rather thanlist[str]/dict[str, int]so callers can pass tuples or read-only views. cast()is a no-op at runtime: It only silences the type checker; useisinstance()orTypeGuard/TypeIswhen you need an actual runtime check.- Avoid
Anywhenobjectworks:Anydisables type checking silently;objectforces callers to narrow the type safely.
Common Functions
- typing.AbstractSet() —
AbstractSet(*args, **kwargs)— Deprecated alias to collections.abc.Set. - typing.Annotated() —
Annotated(*args, **kwds)— Add context-specific metadata to a type. - typing.assert_never() —
assert_never(arg: Never, /) -> Never— Statically assert that a line of code is unreachable. - typing.assert_type() —
assert_type(val, typ, /)— Ask a static type checker to confirm that the value is of the given type. - typing.AsyncContextManager() —
AsyncContextManager(*args, **kwargs)— Deprecated alias to contextlib.AbstractAsyncContextManager. - typing.AsyncGenerator() —
AsyncGenerator(*args, **kwargs)— Deprecated alias to collections.abc.AsyncGenerator. - typing.AsyncIterable() —
AsyncIterable(*args, **kwargs)— Deprecated alias to collections.abc.AsyncIterable. - typing.AsyncIterator() —
AsyncIterator(*args, **kwargs)— Deprecated alias to collections.abc.AsyncIterator. - typing.Awaitable() —
Awaitable(*args, **kwargs)— Deprecated alias to collections.abc.Awaitable. - typing.ByteString() —
ByteString(*args, **kwargs)— Deprecated alias to collections.abc.ByteString. - typing.Callable() —
Callable(*args, **kwargs)— Deprecated alias to collections.abc.Callable. - typing.cast() —
cast(typ, val)— Cast a value to a type. - typing.ChainMap() —
ChainMap(*args, **kwargs)— Deprecated alias to collections.ChainMap. - typing.ClassVar() —
ClassVar(*args, **kwds)— Special type construct to mark class variables. - typing.clear_overloads() —
clear_overloads()— Clear all overloads in the registry. - typing.Collection() —
Collection(*args, **kwargs)— Deprecated alias to collections.abc.Collection. - typing.Concatenate() —
Concatenate(*args, **kwds)— Special form for annotating higher-order functions. - typing.Container() —
Container(*args, **kwargs)— Deprecated alias to collections.abc.Container. - typing.ContextManager() —
ContextManager(*args, **kwargs)— Deprecated alias to contextlib.AbstractContextManager. - typing.Coroutine() —
Coroutine(*args, **kwargs)— Deprecated alias to collections.abc.Coroutine. - typing.Counter() —
Counter(*args, **kwargs)— Deprecated alias to collections.Counter. - typing.dataclass_transform() —
dataclass_transform(*, eq_default: bool = True, order_default: bool = False, kw_only_default: bool = False, frozen_default: bool = False, field_specifiers: tuple[type[typing.Any] | typing.Callable[..., typing.Any], ...] = (), **kwargs: Any) -> <class '_IdentityCallable'>— Decorator to mark an object as providing dataclass-like behavior. - typing.DefaultDict() —
DefaultDict(*args, **kwargs)— Deprecated alias to collections.defaultdict. - typing.Deque() —
Deque(*args, **kwargs)— Deprecated alias to collections.deque. - typing.Dict() —
Dict(*args, **kwargs)— Deprecated alias to dict. - typing.evaluate_forward_ref() —
evaluate_forward_ref(forward_ref, *, owner=None, globals=None, locals=None, type_params=None, format=None, _recursive_guard=frozenset())— Evaluate a forward reference as a type hint. - typing.Final() —
Final(*args, **kwds)— Special typing construct to indicate final names to type checkers. - typing.final() —
final(f)— Decorator to indicate final methods and final classes. - typing.FrozenSet() —
FrozenSet(*args, **kwargs)— Deprecated alias to frozenset. - typing.Generator() —
Generator(*args, **kwargs)— Deprecated alias to collections.abc.Generator. - typing.get_args() —
get_args(tp)— Get type arguments with all substitutions performed. - typing.get_origin() —
get_origin(tp)— Get the unsubscripted version of a type. - typing.get_overloads() —
get_overloads(func)— Return all defined overloads for func as a sequence. - typing.get_protocol_members() —
get_protocol_members(tp: type, /) -> frozenset[str]— Return the set of members defined in a Protocol. - typing.get_type_hints() —
get_type_hints(obj, globalns=None, localns=None, include_extras=False, *, format=None)— Return type hints for an object.
Classes & Objects
- typing.Any — Special type indicating an unconstrained type.
- typing.BinaryIO — Typed approximation of the return of open() in binary mode. (Methods:
.close(),.closed(),.fileno(),.flush(),.isatty(),.mode()) - typing.ForwardRef — Wrapper that holds a forward reference. (Methods:
.evaluate()) - typing.Generic — Abstract base class for generic types.
- typing.IO — Generic base class for TextIO and BinaryIO. (Methods:
.close(),.closed(),.fileno(),.flush(),.isatty(),.mode()) - typing.NewType — NewType creates simple unique types with almost zero runtime overhead.
- typing.ParamSpec — Parameter specification variable. (Methods:
.has_default()) - typing.ParamSpecArgs — The args for a ParamSpec object.
- typing.ParamSpecKwargs — The kwargs for a ParamSpec object.
- typing.Protocol — Base class for protocol classes.
- typing.SupportsAbs — A protocol with one abstract method abs that is covariant in its return type.
- typing.SupportsBytes — A protocol with one abstract method bytes.
- typing.SupportsComplex — A protocol with one abstract method complex.
- typing.SupportsFloat — A protocol with one abstract method float.
- typing.SupportsIndex — A protocol with one abstract method index.
- typing.SupportsInt — A protocol with one abstract method int.
- typing.SupportsRound — A protocol with one abstract method round that is covariant in its return type.
- typing.Text — str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer (Methods:
.capitalize(),.casefold(),.center(),.count(),.encode(),.endswith()) - typing.TextIO — Typed approximation of the return of open() in text mode. (Methods:
.buffer(),.close(),.closed(),.encoding(),.errors(),.fileno()) - typing.TypeAliasType — Type alias.
Constants & Attributes
typing.AnyStr(TypeVar) =~AnyStrtyping.NoDefault(NoDefaultType) =typing.NoDefaulttyping.TYPE_CHECKING(bool) =False
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/abc
- tuts/python3/stdlib_module/annotationlib
- tuts/python3/stdlib_module/bdb
- tuts/python3/stdlib_module/cProfile
- tuts/python3/stdlib_module/dataclasses
- tuts/python3/stdlib_module/doctest
- tuts/python3/stdlib_module/faulthandler
- tuts/python3/stdlib_module/pdb
- tuts/python3/stdlib_module/profile
- tuts/python3/stdlib_module/pstats
- tuts/python3/stdlib_module/pydoc
- tuts/python3/stdlib_module/pydoc_data
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/timeit
- tuts/python3/stdlib_module/trace
- tuts/python3/stdlib_module/tracemalloc
- tuts/python3/stdlib_module/types
- tuts/python3/stdlib_module/typing/AbstractSet
- tuts/python3/stdlib_module/typing/Annotated
- tuts/python3/stdlib_module/typing/Any
- tuts/python3/stdlib_module/typing/assert_never
- tuts/python3/stdlib_module/typing/assert_type
- tuts/python3/stdlib_module/typing/AsyncContextManager
- tuts/python3/stdlib_module/typing/AsyncGenerator
- tuts/python3/stdlib_module/typing/AsyncIterable
- tuts/python3/stdlib_module/typing/AsyncIterator
- tuts/python3/stdlib_module/typing/Awaitable
- tuts/python3/stdlib_module/typing/BinaryIO
- tuts/python3/stdlib_module/typing/ByteString
- tuts/python3/stdlib_module/typing/Callable
- tuts/python3/stdlib_module/typing/cast
- tuts/python3/stdlib_module/typing/ChainMap
- tuts/python3/stdlib_module/typing/ClassVar
- tuts/python3/stdlib_module/typing/clear_overloads
- tuts/python3/stdlib_module/typing/Collection
- tuts/python3/stdlib_module/typing/Concatenate
- tuts/python3/stdlib_module/typing/Container
- tuts/python3/stdlib_module/typing/ContextManager
- tuts/python3/stdlib_module/typing/Coroutine
- tuts/python3/stdlib_module/typing/Counter
- tuts/python3/stdlib_module/typing/dataclass_transform
- tuts/python3/stdlib_module/typing/DefaultDict
- tuts/python3/stdlib_module/typing/Deque
- tuts/python3/stdlib_module/typing/Dict
- tuts/python3/stdlib_module/typing/evaluate_forward_ref
- tuts/python3/stdlib_module/typing/Final
- tuts/python3/stdlib_module/typing/final_func
- tuts/python3/stdlib_module/typing/ForwardRef
- tuts/python3/stdlib_module/typing/FrozenSet
- tuts/python3/stdlib_module/typing/Generator
- tuts/python3/stdlib_module/typing/Generic
- tuts/python3/stdlib_module/typing/get_args
- tuts/python3/stdlib_module/typing/get_origin
- tuts/python3/stdlib_module/typing/get_overloads
- tuts/python3/stdlib_module/typing/get_protocol_members
- tuts/python3/stdlib_module/typing/get_type_hints
- tuts/python3/stdlib_module/typing/IO
- tuts/python3/stdlib_module/typing/NewType
- tuts/python3/stdlib_module/typing/ParamSpec
- tuts/python3/stdlib_module/typing/ParamSpecArgs
- tuts/python3/stdlib_module/typing/ParamSpecKwargs
- tuts/python3/stdlib_module/typing/Protocol
- tuts/python3/stdlib_module/typing/SupportsAbs
- tuts/python3/stdlib_module/typing/SupportsBytes
- tuts/python3/stdlib_module/typing/SupportsComplex
- tuts/python3/stdlib_module/typing/SupportsFloat
- tuts/python3/stdlib_module/typing/SupportsIndex
- tuts/python3/stdlib_module/typing/SupportsInt
- tuts/python3/stdlib_module/typing/SupportsRound
- tuts/python3/stdlib_module/typing/Text
- tuts/python3/stdlib_module/typing/TextIO
- tuts/python3/stdlib_module/typing/TypeAliasType
- tuts/python3/stdlib_module/unicodedata
- tuts/python3/stdlib_module/unittest
- tuts/python3/tutorials/intermediate_python_and_software_engineering
- tuts/python3/tutorials/intermediate_python_and_software_engineering/modern_data_modeling
- tuts/python3/tutorials/intermediate_python_and_software_engineering/type_hinting_and_static_analysis
Related notes
- tuts/python3/stdlib_module/annotationlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/doctest Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pydoc Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pydoc_data Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/types Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/typing/AbstractSet Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/typing/Annotated Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/typing/Any Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/typing/assert_never Linked here; links to this page; shared tags: #stdlib