Тема: 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.
-
Обобщённые функции и декораторы с TypeVar, ParamSpec и синтаксисом PEP 695
Переменная типа связывает типы параметров и возвращаемых значений. Скобки PEP 695 (def f[T](...)) заменяют ручные объявления TypeVar; верхняя граница и ограничение набором типов имеют разную семантику, а ParamSpec позволяет декоратору сохранить сигнатуру оборачиваемой функции, не стирая её до Callable[..., Any].
Машиночитаемо: JSON