Topic: typing
-
Protocol classes: structural typing for duck-typed Python
A typing.Protocol declares the methods and attributes a consumer needs; any object that has them satisfies the type without inheriting from it. Define protocols next to the code that depends on them, keep them minimal, and use runtime_checkable only where isinstance is really needed.
-
Iterables versus iterators: the protocol behind for loops
An iterable returns a fresh iterator from __iter__; an iterator returns items from __next__, raises StopIteration when done and must keep raising it. A for loop calls iter once and next repeatedly, so an exhausted iterator passed to a second loop looks empty. Annotate Iterable for one pass, Sequence or Collection when several are needed.
-
Generic functions and decorators with TypeVar, ParamSpec and the PEP 695 syntax
A type variable links the types of parameters and return values; PEP 695 brackets (def f[T](...)) replace manual TypeVar declarations, bounds and constraints have different semantics, and ParamSpec lets a decorator preserve the signature of the function it wraps instead of erasing it to Callable[..., Any].
Machine-readable: JSON