主题: 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