On this page
  1. typing
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Structural Subtyping with Protocol & TypedDict
  7. 2. Preserving Signatures on Decorators with ParamSpec (or PEP 695)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

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

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes