テーマ: 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