typing --- 型ヒントのサポート¶
バージョン 3.5 で追加.
ソースコード: Lib/typing.py
注釈
Python ランタイムは、関数や変数の型アノテーションを強制しません。型アノテーションは、型チェッカー、IDE、linterなどのサードパーティーツールで使われます。
このモジュールは型のランタイムへのサポートを提供します。最も基本的な型として:data:Any、Union、CallableTypeVar、Generic が存在します。詳細な仕様は:pep:`484`に記載があります。型ヒントの導入についての説明は:pep:`483`に記載があります。
以下の関数は文字列を受け取って文字列を返す関数で、次のようにアノテーションがつけられます:
def greeting(name: str) -> str:
return 'Hello ' + name
関数 greeting で、実引数 name の型は str であり、返り値の型は str であることが期待されます。サブタイプも実引数として許容されます。
typing モジュールには新しい機能が頻繁に追加されています。 typing_extensions パッケージは、古いバージョンの Python への新しい機能のバックポートを提供しています。
参考
For a quick overview of type hints, refer to this cheat sheet.
The "Type System Reference" section of https://mypy.readthedocs.io/ -- since the Python typing system is standardised via PEPs, this reference should broadly apply to most Python type checkers, although some parts may still be specific to mypy.
The documentation at https://typing.readthedocs.io/ serves as useful reference for type system features, useful typing related tools and typing best practices.
関連する PEP¶
Since the initial introduction of type hints in PEP 484 and PEP 483, a number of PEPs have modified and enhanced Python's framework for type annotations. These include:
- PEP 544: Protocols: Structural subtyping (static duck typing)
Protocolと、@runtime_checkableのデコレーターの導入
- PEP 585: Type Hinting Generics In Standard Collections
types.GenericAliasと、標準ライブラリのクラスを ジェネリック型 として利用する機能の導入
- PEP 604: Allow writing union types as
X | Y types.UnionTypeと、二項論理和演算子|で ユニオン型 を表す機能の導入
- PEP 604: Allow writing union types as
- PEP 612: Parameter Specification Variables
ParamSpecとConcatenateの導入
型エイリアス¶
型エイリアスは、型をエイリアスに割り当てて定義されます。
この例では、Vector と list[float] が置き換え可能な同義語として扱われます:
Vector = list[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
型エイリアスは複雑な型シグネチャを単純化するのに有用です。例えば:
from collections.abc import Sequence
ConnectionOptions = dict[str, str]
Address = tuple[str, int]
Server = tuple[Address, ConnectionOptions]
def broadcast_message(message: str, servers: Sequence[Server]) -> None:
...
# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
message: str,
servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
...
型ヒントとしての None は特別なケースであり、 type(None) によって置き換えられます。
NewType¶
異なる型を作るためには NewType ヘルパークラスを使います:
from typing import NewType
UserId = NewType('UserId', int)
some_id = UserId(524313)
静的型チェッカーは新しい型を元々の型のサブクラスのように扱います。この振る舞いは論理的な誤りを見つける手助けとして役に立ちます。
def get_user_name(user_id: UserId) -> str:
...
# passes type checking
user_a = get_user_name(UserId(42351))
# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
UserId 型の変数も int の全ての演算が行えますが、その結果は常に int 型になります。
この振る舞いにより、 int が期待されるところに UserId を渡せますが、不正な方法で UserId を作ってしまうことを防ぎます。
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
これらのチェックは静的型チェッカーのみによって強制されるということに注意してください。
実行時に Derived = NewType('Derived', Base) という文は渡された仮引数をただちに返す Derived callable を作ります。
つまり Derived(some_value) という式は新しいクラスを作ることはなく、通常の関数呼び出しより多くのオーバーヘッドがないということを意味します。
より正確に言うと、式 some_value is Derived(some_value) は実行時に常に真を返します。
Derived のサブタイプを作成することはできません
from typing import NewType
UserId = NewType('UserId', int)
# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
しかし、 'derived' である NewType をもとにした NewType は作ることが出来ます:
from typing import NewType
UserId = NewType('UserId', int)
ProUserId = NewType('ProUserId', UserId)
そして ProUserId に対する型検査は期待通りに動作します。
より詳しくは PEP 484 を参照してください。
注釈
型エイリアスの使用は二つの型が互いに 等価 だと宣言している、ということを思い出してください。 Alias = Original とすると、静的型検査器は Alias をすべての場合において Original と 完全に等価 なものとして扱います。これは複雑な型シグネチャを単純化したい時に有用です。
これに対し、 NewType はある型をもう一方の型の サブタイプ として宣言します。 Derived = NewType('Derived', Original) とすると静的型検査器は Derived を Original の サブクラス として扱います。つまり Original 型の値は Derived 型の値が期待される場所で使うことが出来ないということです。これは論理的な誤りを最小の実行時のコストで防ぎたい時に有用です。
バージョン 3.5.2 で追加.
バージョン 3.10 で変更: NewType is now a class rather than a function. There is some additional
runtime cost when calling NewType over a regular function. However, this
cost will be reduced in 3.11.0.
呼び出し可能オブジェクト¶
特定のシグネチャを持つコールバック関数を要求されるフレームワークでは、 Callable[[Arg1Type, Arg2Type], ReturnType] を使って型ヒントを付けます。
例えば:
from collections.abc import Callable
def feeder(get_next_item: Callable[[], str]) -> None:
# Body
def async_query(on_success: Callable[[int], None],
on_error: Callable[[int, Exception], None]) -> None:
# Body
async def on_update(value: str) -> None:
# Body
callback: Callable[[str], Awaitable[None]] = on_update
型ヒントの実引数の型を ellipsis で置き換えることで呼び出しシグニチャを指定せずに callable の戻り値の型を宣言することができます: Callable[..., ReturnType]。
callable が別の callable を引数に取る場合は、ParamSpec を使えば両者のパラメータ引数の依存関係を表現することができます。
さらに、ある callable が別の callable から引数を追加したり削除したりする場合は、 Concatenate 演算子を使うことで表現できます。
その場合、callable の型は Callable[ParamSpecVariable, ReturnType] と Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType] という形になります。
バージョン 3.10 で変更: Callable は ParamSpec と Concatenate をサポートしました。詳細は PEP 612 を参照してください。
参考
ParamSpec と Concatenate のドキュメントに、Callable での使用例が記載されています。
ジェネリクス¶
コンテナ内のオブジェクトについての型情報は一般的な方法では静的に推論できないため、抽象基底クラスを継承したクラスが実装され、期待されるコンテナの要素の型を示すために添字表記をサポートするようになりました。
from collections.abc import Mapping, Sequence
def notify_by_email(employees: Sequence[Employee],
overrides: Mapping[str, str]) -> None: ...
ジェネリクスは、 typing にある TypeVar と呼ばれるファクトリを使ってパラメータ化することができます。
from collections.abc import Sequence
from typing import TypeVar
T = TypeVar('T') # Declare type variable
def first(l: Sequence[T]) -> T: # Generic function
return l[0]
ユーザー定義のジェネリック型¶
ユーザー定義のクラスを、ジェネリッククラスとして定義できます。
from typing import TypeVar, Generic
from logging import Logger
T = TypeVar('T')
class LoggedVar(Generic[T]):
def __init__(self, value: T, name: str, logger: Logger) -> None:
self.name = name
self.logger = logger
self.value = value
def set(self, new: T) -> None:
self.log('Set ' + repr(self.value))
self.value = new
def get(self) -> T:
self.log('Get ' + repr(self.value))
return self.value
def log(self, message: str) -> None:
self.logger.info('%s: %s', self.name, message)
Generic[T] を基底クラスにすることで、 LoggedVar クラスが 1 つの型引数 T をとる、と定義できます。
この定義により、クラスの本体の中でも T が型として有効になります。
Generic 基底クラスは LoggedVar[T] が型として有効になるように __class_getitem__() メソッドを定義しています:
from collections.abc import Iterable
def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:
for var in vars:
var.set(0)
A generic type can have any number of type variables. All varieties of
TypeVar are permissible as parameters for a generic type:
from typing import TypeVar, Generic, Sequence
T = TypeVar('T', contravariant=True)
B = TypeVar('B', bound=Sequence[bytes], covariant=True)
S = TypeVar('S', int, str)
class WeirdTrio(Generic[T, B, S]):
...
Generic の引数のそれぞれの型変数は別のものでなければなりません。このため次のクラス定義は無効です:
from typing import TypeVar, Generic
...
T = TypeVar('T')
class Pair(Generic[T, T]): # INVALID
...
Generic を用いて多重継承が可能です:
from collections.abc import Sized
from typing import TypeVar, Generic
T = TypeVar('T')
class LinkedList(Sized, Generic[T]):
...
ジェネリッククラスを継承するとき、いくつかの型変数を固定することが出来ます:
from collections.abc import Mapping
from typing import TypeVar
T = TypeVar('T')
class MyDict(Mapping[str, T]):
...
この場合では MyDict は仮引数 T を 1 つとります。
型引数を指定せずにジェネリッククラスを使う場合、それぞれの型引数に Any を与えられたものとして扱います。
次の例では、MyIterable はジェネリックではありませんが Iterable[Any] を暗黙的に継承しています:
from collections.abc import Iterable
class MyIterable(Iterable): # Same as Iterable[Any]
ユーザ定義のジェネリック型エイリアスもサポートされています。例:
from collections.abc import Iterable
from typing import TypeVar
S = TypeVar('S')
Response = Iterable[S] | int
# Return type here is same as Iterable[str] | int
def response(query: str) -> Response[str]:
...
T = TypeVar('T', int, float, complex)
Vec = Iterable[tuple[T, T]]
def inproduct(v: Vec[T]) -> T: # Same as Iterable[tuple[T, T]]
return sum(x*y for x, y in v)
バージョン 3.7 で変更: Generic にあった独自のメタクラスは無くなりました。
User-defined generics for parameter expressions are also supported via parameter
specification variables in the form Generic[P]. The behavior is consistent
with type variables' described above as parameter specification variables are
treated by the typing module as a specialized type variable. The one exception
to this is that a list of types can be used to substitute a ParamSpec:
>>> from typing import Generic, ParamSpec, TypeVar
>>> T = TypeVar('T')
>>> P = ParamSpec('P')
>>> class Z(Generic[T, P]): ...
...
>>> Z[int, [dict, float]]
__main__.Z[int, (<class 'dict'>, <class 'float'>)]
Furthermore, a generic with only one parameter specification variable will accept
parameter lists in the forms X[[Type1, Type2, ...]] and also
X[Type1, Type2, ...] for aesthetic reasons. Internally, the latter is converted
to the former, so the following are equivalent:
>>> class X(Generic[P]): ...
...
>>> X[int, str]
__main__.X[(<class 'int'>, <class 'str'>)]
>>> X[[int, str]]
__main__.X[(<class 'int'>, <class 'str'>)]
Do note that generics with ParamSpec may not have correct
__parameters__ after substitution in some cases because they
are intended primarily for static type checking.
バージョン 3.10 で変更: Generic can now be parameterized over parameter expressions.
See ParamSpec and PEP 612 for more details.
A user-defined generic class can have ABCs as base classes without a metaclass conflict. Generic metaclasses are not supported. The outcome of parameterizing generics is cached, and most types in the typing module are hashable and comparable for equality.
Any 型¶
Any は特別な種類の型です。静的型検査器はすべての型を Any と互換として扱い、 Any をすべての型と互換として扱います。
これは、 Any 型の値では、任意の演算やメソッドの呼び出しが行えることを意味します:
from typing import Any
a: Any = None
a = [] # OK
a = 2 # OK
s: str = ''
s = a # OK
def foo(item: Any) -> int:
# Passes type checking; 'item' could be any type,
# and that type might have a 'bar' method
item.bar()
...
Any 型の値をより詳細な型に代入する時に型検査が行われないことに注意してください。例えば、静的型検査器は a を s に代入する時、s が str 型として宣言されていて実行時に int の値を受け取るとしても、エラーを報告しません。
さらに、返り値や引数の型のないすべての関数は暗黙的に Any を使用します。
def legacy_parser(text):
...
return data
# A static type checker will treat the above
# as having the same signature as:
def legacy_parser(text: Any) -> Any:
...
return data
この挙動により、動的型付けと静的型付けが混在したコードを書かなければならない時に Any を 非常口 として使用することができます。
Any の挙動と object の挙動を対比しましょう。 Any と同様に、すべての型は object のサブタイプです。しかしながら、 Any と異なり、逆は成り立ちません: object はすべての他の型のサブタイプでは ありません。
これは、ある値の型が object のとき、型検査器はこれについてのほとんどすべての操作を拒否し、これをより特殊化された変数に代入する (または返り値として利用する) ことは型エラーになることを意味します。例えば:
def hash_a(item: object) -> int:
# Fails type checking; an object does not have a 'magic' method.
item.magic()
...
def hash_b(item: Any) -> int:
# Passes type checking
item.magic()
...
# Passes type checking, since ints and strs are subclasses of object
hash_a(42)
hash_a("foo")
# Passes type checking, since Any is compatible with all types
hash_b(42)
hash_b("foo")
object は、ある値が型安全な方法で任意の型として使えることを示すために使用します。 Any はある値が動的に型付けられることを示すために使用します。
名前的部分型 vs 構造的部分型¶
初めは PEP 484 は Python の静的型システムを 名前的部分型 を使って定義していました。
名前的部分型とは、クラス B が期待されているところにクラス A が許容されるのは A が B のサブクラスの場合かつその場合に限る、ということです。
前出の必要条件は、Iterable などの抽象基底クラスにも当て嵌まります。
この型付け手法の問題は、この手法をサポートするためにクラスに明確な型付けを行う必要があることで、これは pythonic ではなく、普段行っている 慣用的な Python コードへの動的型付けとは似ていません。
例えば、次のコードは PEP 484 に従ったものです
from collections.abc import Sized, Iterable, Iterator
class Bucket(Sized, Iterable[int]):
...
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[int]: ...
PEP 544 によって上にあるようなクラス定義で基底クラスを明示しないコードをユーザーが書け、静的型チェッカーで Bucket が Sized と Iterable[int] 両方のサブタイプだと暗黙的に見なせるようになり、この問題が解決しました。
これは structural subtyping (構造的部分型) (あるいは、静的ダックタイピング) として知られています:
from collections.abc import Iterator, Iterable
class Bucket: # Note: no base classes
...
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[int]: ...
def collect(items: Iterable[int]) -> int: ...
result = collect(Bucket()) # Passes type check
さらに、特別なクラス Protocol のサブクラスを作ることで、新しい独自のプロトコルを作って構造的部分型というものを満喫できます。
モジュールの内容¶
このモジュールでは以下のクラス、関数、デコレータを定義します。
注釈
このモジュールは、既存の標準ライブラリクラスのサブクラスかつ、 [] 内の型変数をサポートするために Generic を拡張している、いくつかの型を定義しています。
これらの型は、既存の相当するクラスが [] をサポートするように拡張されたときに Python 3.9 で廃止になりました。
余計な型は Python 3.9 で非推奨になりましたが、非推奨の警告はどれもインタープリタから通告されません。 型チェッカーがチェックするプログラムの対照が Python 3.9 もしくはそれ以降のときに、非推奨の型に目印を付けることが期待されています。
非推奨の型は、Python 3.9.0 のリリースから5年後の初めての Python バージョンで typing モジュールから削除されます。
詳しいことは PEP 585—Type Hinting Generics In Standard Collections を参照してください。
特殊型付けプリミティブ¶
特殊型¶
これらはアノテーションの内部の型として使えますが、[] はサポートしていません。
-
typing.NoReturn¶ 関数が返り値を持たないことを示す特別な型です。例えば次のように使います:
from typing import NoReturn def stop() -> NoReturn: raise RuntimeError('no way')
バージョン 3.5.4 で追加.
バージョン 3.6.2 で追加.
-
typing.TypeAlias¶ Special annotation for explicitly declaring a type alias. For example:
from typing import TypeAlias Factors: TypeAlias = list[int]
See PEP 613 for more details about explicit type aliases.
バージョン 3.10 で追加.
特殊形式¶
これらは [] を使ったアノテーションの内部の型として使え、それぞれ固有の文法があります。
-
typing.Tuple¶ タプル型;
Tuple[X, Y]は、最初の要素の型が X で、2つ目の要素の型が Y であるような、2つの要素を持つタプルの型です。 空のタプルの型はTuple[()]と書けます。例:
Tuple[T1, T2]は型変数 T1 と T2 に対応する2つの要素を持つタプルです。Tuple[int, float, str]は int と float、 string のタプルです。同じ型の任意の長さのタプルを指定するには ellipsis リテラルを用います。例:
Tuple[int, ...]。ただのTupleはTuple[Any, ...]と等価で、さらにtupleと等価です。.バージョン 3.9 で非推奨:
builtins.tupleは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
typing.Union¶ ユニオン型;
Union[X, Y]はX | Yと等価で X または Y を表します。To define a union, use e.g.
Union[int, str]or the shorthandint | str. Using that shorthand is recommended. Details:引数は型でなければならず、少なくとも一つ必要です。
ユニオン型のユニオン型は平滑化されます。例えば:
Union[Union[int, str], float] == Union[int, str, float]
引数が一つのユニオン型は消えます。例えば:
Union[int] == int # The constructor actually returns int
冗長な実引数は飛ばされます。例えば:
Union[int, str, int] == Union[int, str] == int | str
ユニオン型を比較するとき引数の順序は無視されます。例えば:
Union[int, str] == Union[str, int]
Unionのサブクラスを作成したり、インスタンスを作成することは出来ません。Union[X][Y]と書くことは出来ません。
バージョン 3.7 で変更: 明示的に書かれているサブクラスを、実行時に直和型から取り除かなくなりました。
バージョン 3.10 で変更: ユニオン型は
X | Yのように書けるようになりました。 union型の表現 を参照ください。
-
typing.Optional¶ オプショナル型。
Optional[X]はX | None(やUnion[X, None]) と同等です。これがデフォルト値を持つオプション引数とは同じ概念ではないということに注意してください。 デフォルト値を持つオプション引数はオプション引数であるために、型アノテーションに
Optional修飾子は必要ありません。 例えば次のようになります:def foo(arg: int = 0) -> None: ...
それとは逆に、
Noneという値が許されていることが明示されている場合は、引数がオプションであろうとなかろうと、Optionalを使うのが好ましいです。 例えば次のようになります:def foo(arg: Optional[int] = None) -> None: ...
バージョン 3.10 で変更: Optionalは
X | Noneのように書けるようになりました。 ref:union型の表現 <types-union> を参照ください。
-
typing.Callable¶ 呼び出し可能型;
Callable[[int], str]は (int) -> str の関数です。添字表記は常に2つの値とともに使われなければなりません: 実引数のリストと返り値の型です。 実引数のリストは型のリストか ellipsis でなければなりません; 返り値の型は単一の型でなければなりません。
オプショナル引数やキーワード引数を表すための文法はありません; そのような関数型はコールバックの型として滅多に使われません。
Callable[..., ReturnType](リテラルの Ellipsis) は任意の個数の引数をとりReturnTypeを返す型ヒントを与えるために使えます。 普通のCallableはCallable[..., Any]と同等で、collections.abc.Callableでも同様です。callable が別の callable を引数に取る場合は、
ParamSpecを使えば両者のパラメータ引数の依存関係を表現することができます。 さらに、ある callable が別の callable から引数を追加したり削除したりする場合は、Concatenate演算子を使うことで表現できます。 その場合、callable の型はCallable[ParamSpecVariable, ReturnType]とCallable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType]という形になります。バージョン 3.9 で非推奨:
collections.abc.Callableは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。バージョン 3.10 で変更:
CallableはParamSpecとConcatenateをサポートしました。詳細は PEP 612 を参照してください。参考
The documentation for
ParamSpecandConcatenateprovide examples of usage withCallable.
-
typing.Concatenate¶ Used with
CallableandParamSpecto type annotate a higher order callable which adds, removes, or transforms parameters of another callable. Usage is in the formConcatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable].Concatenateis currently only valid when used as the first argument to aCallable. The last parameter toConcatenatemust be aParamSpec.For example, to annotate a decorator
with_lockwhich provides athreading.Lockto the decorated function,Concatenatecan be used to indicate thatwith_lockexpects a callable which takes in aLockas the first argument, and returns a callable with a different type signature. In this case, theParamSpecindicates that the returned callable's parameter types are dependent on the parameter types of the callable being passed in:from collections.abc import Callable from threading import Lock from typing import Concatenate, ParamSpec, TypeVar P = ParamSpec('P') R = TypeVar('R') # Use this lock to ensure that only one thread is executing a function # at any time. my_lock = Lock() def with_lock(f: Callable[Concatenate[Lock, P], R]) -> Callable[P, R]: '''A type-safe decorator which provides a lock.''' def inner(*args: P.args, **kwargs: P.kwargs) -> R: # Provide the lock as the first argument. return f(my_lock, *args, **kwargs) return inner @with_lock def sum_threadsafe(lock: Lock, numbers: list[float]) -> float: '''Add a list of numbers together in a thread-safe manner.''' with lock: return sum(numbers) # We don't need to pass in the lock ourselves thanks to the decorator. sum_threadsafe([1.1, 2.2, 3.3])
バージョン 3.10 で追加.
参考
-
class
typing.Type(Generic[CT_co])¶ Cと注釈が付けされた変数はC型の値を受理します。一方でType[C]と注釈が付けられた変数は、そのクラス自身を受理します -- 具体的には、それはCの クラスオブジェクト を受理します。例:a = 3 # Has type 'int' b = int # Has type 'Type[int]' c = type(a) # Also has type 'Type[int]'
Type[C]は共変であることに注意してください:class User: ... class BasicUser(User): ... class ProUser(User): ... class TeamUser(User): ... # Accepts User, BasicUser, ProUser, TeamUser, ... def make_new_user(user_class: Type[User]) -> User: # ... return user_class()
Type[C]が共変だということは、Cの全てのサブクラスは、Cと同じシグネチャのコンストラクタとクラスメソッドを実装すべきだということになります。 型チェッカーはこの規則への違反に印を付けるべきですが、サブクラスでのコンストラクタ呼び出しで、指定された基底クラスのコンストラクタ呼び出しに適合するものは許可すべきです。 この特別な場合を型チェッカーがどう扱うべきかについては、 PEP 484 の将来のバージョンで変更されるかもしれません。Typeで許されているパラメータは、クラス、Any、 型変数 あるいは、それらの直和型だけです。 例えば次のようになります:def new_non_team_user(user_class: Type[BasicUser | ProUser]): ...
Type[Any]はTypeと等価で、同様にTypeはtypeと等価です。typeは Python のメタクラス階層のルートです。バージョン 3.5.2 で追加.
バージョン 3.9 で非推奨:
builtins.typeは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
typing.Literal¶ 型チェッカーに、変数や関数引数と対応する与えられたリテラル (あるいはいくつかあるリテラルのうちの 1 つ) が同等な値を持つことを表すのに使える型です。
def validate_simple(data: Any) -> Literal[True]: # always returns True ... MODE = Literal['r', 'rb', 'w', 'wb'] def open_helper(file: str, mode: MODE) -> str: ... open_helper('/some/path', 'r') # Passes type check open_helper('/other/path', 'typo') # Error in type checker
Literal[...]はサブクラスにはできません。 実行時に、任意の値がLiteral[...]の型引数として使えますが、型チェッカーが制約を課すことがあります。 リテラル型についてより詳しいことは PEP 586 を参照してください。バージョン 3.8 で追加.
-
typing.ClassVar¶ クラス変数であることを示す特別な型構築子です。
PEP 526 で導入された通り、 ClassVar でラップされた変数アノテーションによって、ある属性はクラス変数として使うつもりであり、そのクラスのインスタンスから設定すべきではないということを示せます。使い方は次のようになります:
class Starship: stats: ClassVar[dict[str, int]] = {} # class variable damage: int = 10 # instance variable
ClassVarは型のみを受け入れ、それ以外は受け付けられません。ClassVarはクラスそのものではなく、isinstance()やissubclass()で使うべきではありません。ClassVarは Python の実行時の挙動を変えませんが、サードパーティの型検査器で使えます。 例えば、型チェッカーは次のコードをエラーとするかもしれません:enterprise_d = Starship(3000) enterprise_d.stats = {} # Error, setting class variable on instance Starship.stats = {} # This is OK
バージョン 3.5.3 で追加.
-
typing.Final¶ 特別な型付けの構成要素で、名前の割り当て直しやサブクラスでのオーバーライドができないことを型チェッカーに示すためのものです。 例えば:
MAX_SIZE: Final = 9000 MAX_SIZE += 1 # Error reported by type checker class Connection: TIMEOUT: Final[int] = 10 class FastConnector(Connection): TIMEOUT = 1 # Error reported by type checker
この機能は実行時には検査されません。詳細については PEP 591 を参照してください。
バージョン 3.8 で追加.
-
typing.Annotated¶ PEP 593 (
Flexible function and variable annotations) で導入された型で、コンテキストに特定のメタデータ (もしかすると、可変個引数のAnnotatedになるメタデータの複数の破片) を持つ既存の型を装飾します。 具体的には、型TはAnnotated[T, x]という型ヒントでメタデータxの注釈を付けられます。 メタデータは静的解析でも実行時解析でも使用できます。 ライブラリ (あるいはツール) に型ヒントAnnotated[T, x]が出てきて、メタデータxに特別なロジックが無い場合は、メタデータxは無視され、この型はTとして扱われるだけです。 関数やクラス上のアノテーションの型検査を一切しなくなる現時点のtypingモジュールにあるno_type_checkの機能とは違って、Annotated型はTの (安全にxを無視できる) 静的型検査も、特定のアプリケーション内のxへの実行時のアクセスも許可されています。Ultimately, the responsibility of how to interpret the annotations (if at all) is the responsibility of the tool or library encountering the
Annotatedtype. A tool or library encountering anAnnotatedtype can scan through the annotations to determine if they are of interest (e.g., usingisinstance()).When a tool or a library does not support annotations or encounters an unknown annotation it should just ignore it and treat annotated type as the underlying type.
It's up to the tool consuming the annotations to decide whether the client is allowed to have several annotations on one type and how to merge those annotations.
Since the
Annotatedtype allows you to put several annotations of the same (or different) type(s) on any node, the tools or libraries consuming those annotations are in charge of dealing with potential duplicates. For example, if you are doing value range analysis you might allow this:T1 = Annotated[int, ValueRange(-10, 5)] T2 = Annotated[T1, ValueRange(-20, 3)]
Passing
include_extras=Truetoget_type_hints()lets one access the extra annotations at runtime.The details of the syntax:
The first argument to
Annotatedmust be a valid typeMultiple type annotations are supported (
Annotatedsupports variadic arguments):Annotated[int, ValueRange(3, 10), ctype("char")]
Annotatedmust be called with at least two arguments (Annotated[int]is not valid)The order of the annotations is preserved and matters for equality checks:
Annotated[int, ValueRange(3, 10), ctype("char")] != Annotated[ int, ctype("char"), ValueRange(3, 10) ]
Nested
Annotatedtypes are flattened, with metadata ordered starting with the innermost annotation:Annotated[Annotated[int, ValueRange(3, 10)], ctype("char")] == Annotated[ int, ValueRange(3, 10), ctype("char") ]
Duplicated annotations are not removed:
Annotated[int, ValueRange(3, 10)] != Annotated[ int, ValueRange(3, 10), ValueRange(3, 10) ]
Annotatedcan be used with nested and generic aliases:T = TypeVar('T') Vec = Annotated[list[tuple[T, T]], MaxLen(10)] V = Vec[int] V == Annotated[list[tuple[int, int]], MaxLen(10)]
バージョン 3.9 で追加.
-
typing.TypeGuard¶ Special typing form used to annotate the return type of a user-defined type guard function.
TypeGuardonly accepts a single type argument. At runtime, functions marked this way should return a boolean.TypeGuardaims to benefit type narrowing -- a technique used by static type checkers to determine a more precise type of an expression within a program's code flow. Usually type narrowing is done by analyzing conditional code flow and applying the narrowing to a block of code. The conditional expression here is sometimes referred to as a "type guard":def is_str(val: str | float): # "isinstance" type guard if isinstance(val, str): # Type of ``val`` is narrowed to ``str`` ... else: # Else, type of ``val`` is narrowed to ``float``. ...
Sometimes it would be convenient to use a user-defined boolean function as a type guard. Such a function should use
TypeGuard[...]as its return type to alert static type checkers to this intention.Using
-> TypeGuardtells the static type checker that for a given function:The return value is a boolean.
If the return value is
True, the type of its argument is the type insideTypeGuard.
例えば:
def is_str_list(val: List[object]) -> TypeGuard[List[str]]: '''Determines whether all objects in the list are strings''' return all(isinstance(x, str) for x in val) def func1(val: List[object]): if is_str_list(val): # Type of ``val`` is narrowed to ``List[str]``. print(" ".join(val)) else: # Type of ``val`` remains as ``List[object]``. print("Not a list of strings!")
If
is_str_listis a class or instance method, then the type inTypeGuardmaps to the type of the second parameter afterclsorself.In short, the form
def foo(arg: TypeA) -> TypeGuard[TypeB]: ..., means that iffoo(arg)returnsTrue, thenargnarrows fromTypeAtoTypeB.注釈
TypeBneed not be a narrower form ofTypeA-- it can even be a wider form. The main reason is to allow for things like narrowingList[object]toList[str]even though the latter is not a subtype of the former, sinceListis invariant. The responsibility of writing type-safe type guards is left to the user.TypeGuardalso works with type variables. See PEP 647 for more details.バージョン 3.10 で追加.
Building generic types¶
These are not used in annotations. They are building blocks for creating generic types.
-
class
typing.Generic¶ ジェネリック型のための抽象基底クラスです。
ジェネリック型は典型的にはこのクラスを1つ以上の型変数によってインスタンス化したものを継承することによって宣言されます。例えば、ジェネリックマップ型は次のように定義することが出来ます:
class Mapping(Generic[KT, VT]): def __getitem__(self, key: KT) -> VT: ... # Etc.
このクラスは次のように使用することが出来ます:
X = TypeVar('X') Y = TypeVar('Y') def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y: try: return mapping[key] except KeyError: return default
-
class
typing.TypeVar¶ 型変数です。
使い方:
T = TypeVar('T') # Can be anything S = TypeVar('S', bound=str) # Can be any subtype of str A = TypeVar('A', str, bytes) # Must be exactly str or bytes
型変数は主として静的型検査器のために存在します。型変数はジェネリック型やジェネリック関数の定義の引数として役に立ちます。ジェネリック型についての詳細は
Genericを参照してください。ジェネリック関数は以下のように動作します:def repeat(x: T, n: int) -> Sequence[T]: """Return a list containing n references to x.""" return [x]*n def print_capitalized(x: S) -> S: """Print x capitalized, and return x.""" print(x.capitalize()) return x def concatenate(x: A, y: A) -> A: """Add two strings or bytes objects together.""" return x + y
Note that type variables can be bound, constrained, or neither, but cannot be both bound and constrained.
Constrained type variables and bound type variables have different semantics in several important ways. Using a constrained type variable means that the
TypeVarcan only ever be solved as being exactly one of the constraints given:a = concatenate('one', 'two') # Ok, variable 'a' has type 'str' b = concatenate(StringSubclass('one'), StringSubclass('two')) # Inferred type of variable 'b' is 'str', # despite 'StringSubclass' being passed in c = concatenate('one', b'two') # error: type variable 'A' can be either 'str' or 'bytes' in a function call, but not both
Using a bound type variable, however, means that the
TypeVarwill be solved using the most specific type possible:print_capitalized('a string') # Ok, output has type 'str' class StringSubclass(str): pass print_capitalized(StringSubclass('another string')) # Ok, output has type 'StringSubclass' print_capitalized(45) # error: int is not a subtype of str
Type variables can be bound to concrete types, abstract types (ABCs or protocols), and even unions of types:
U = TypeVar('U', bound=str|bytes) # Can be any subtype of the union str|bytes V = TypeVar('V', bound=SupportsAbs) # Can be anything with an __abs__ method
Bound type variables are particularly useful for annotating
classmethodsthat serve as alternative constructors. In the following example (by Raymond Hettinger), the type variableCis bound to theCircleclass through the use of a forward reference. Using this type variable to annotate thewith_circumferenceclassmethod, rather than hardcoding the return type asCircle, means that a type checker can correctly infer the return type even if the method is called on a subclass:import math C = TypeVar('C', bound='Circle') class Circle: """An abstract circle""" def __init__(self, radius: float) -> None: self.radius = radius # Use a type variable to show that the return type # will always be an instance of whatever ``cls`` is @classmethod def with_circumference(cls: type[C], circumference: float) -> C: """Create a circle with the specified circumference""" radius = circumference / (math.pi * 2) return cls(radius) class Tire(Circle): """A specialised circle (made out of rubber)""" MATERIAL = 'rubber' c = Circle.with_circumference(3) # Ok, variable 'c' has type 'Circle' t = Tire.with_circumference(4) # Ok, variable 't' has type 'Tire' (not 'Circle')
実行時に、
isinstance(x, T)はTypeErrorを送出するでしょう。一般的に、isinstance()とissubclass()は型に対して使用するべきではありません。Type variables may be marked covariant or contravariant by passing
covariant=Trueorcontravariant=True. See PEP 484 for more details. By default, type variables are invariant.
-
class
typing.ParamSpec(name, *, bound=None, covariant=False, contravariant=False)¶ Parameter specification variable. A specialized version of
type variables.使い方:
P = ParamSpec('P')
Parameter specification variables exist primarily for the benefit of static type checkers. They are used to forward the parameter types of one callable to another callable -- a pattern commonly found in higher order functions and decorators. They are only valid when used in
Concatenate, or as the first argument toCallable, or as parameters for user-defined Generics. SeeGenericfor more information on generic types.For example, to add basic logging to a function, one can create a decorator
add_loggingto log function calls. The parameter specification variable tells the type checker that the callable passed into the decorator and the new callable returned by it have inter-dependent type parameters:from collections.abc import Callable from typing import TypeVar, ParamSpec import logging T = TypeVar('T') P = ParamSpec('P') def add_logging(f: Callable[P, T]) -> Callable[P, T]: '''A type-safe decorator to add logging to a function.''' def inner(*args: P.args, **kwargs: P.kwargs) -> T: logging.info(f'{f.__name__} was called') return f(*args, **kwargs) return inner @add_logging def add_two(x: float, y: float) -> float: '''Add two numbers together.''' return x + y
Without
ParamSpec, the simplest way to annotate this previously was to use aTypeVarwith boundCallable[..., Any]. However this causes two problems:The type checker can't type check the
innerfunction because*argsand**kwargshave to be typedAny.cast()may be required in the body of theadd_loggingdecorator when returning theinnerfunction, or the static type checker must be told to ignore thereturn inner.
-
args¶
-
kwargs¶ Since
ParamSpeccaptures both positional and keyword parameters,P.argsandP.kwargscan be used to split aParamSpecinto its components.P.argsrepresents the tuple of positional parameters in a given call and should only be used to annotate*args.P.kwargsrepresents the mapping of keyword parameters to their values in a given call, and should be only be used to annotate**kwargs. Both attributes require the annotated parameter to be in scope. At runtime,P.argsandP.kwargsare instances respectively ofParamSpecArgsandParamSpecKwargs.
Parameter specification variables created with
covariant=Trueorcontravariant=Truecan be used to declare covariant or contravariant generic types. Theboundargument is also accepted, similar toTypeVar. However the actual semantics of these keywords are yet to be decided.バージョン 3.10 で追加.
注釈
Only parameter specification variables defined in global scope can be pickled.
参考
PEP 612 -- Parameter Specification Variables (the PEP which introduced
ParamSpecandConcatenate).CallableandConcatenate.
-
typing.ParamSpecArgs¶
-
typing.ParamSpecKwargs¶ Arguments and keyword arguments attributes of a
ParamSpec. TheP.argsattribute of aParamSpecis an instance ofParamSpecArgs, andP.kwargsis an instance ofParamSpecKwargs. They are intended for runtime introspection and have no special meaning to static type checkers.Calling
get_origin()on either of these objects will return the originalParamSpec:P = ParamSpec("P") get_origin(P.args) # returns P get_origin(P.kwargs) # returns P
バージョン 3.10 で追加.
-
typing.AnyStr¶ AnyStris aconstrained type variabledefined asAnyStr = TypeVar('AnyStr', str, bytes).他の種類の文字列を混ぜることなく、任意の種類の文字列を許す関数によって使われることを意図しています。
def concat(a: AnyStr, b: AnyStr) -> AnyStr: return a + b concat(u"foo", u"bar") # Ok, output has type 'unicode' concat(b"foo", b"bar") # Ok, output has type 'bytes' concat(u"foo", b"bar") # Error, cannot mix unicode and bytes
-
class
typing.Protocol(Generic)¶ プロトコルクラスの基底クラス。 プロトコルクラスは次のように定義されます:
class Proto(Protocol): def meth(self) -> int: ...
このようなクラスは主に構造的部分型 (静的ダックタイピング) を認識する静的型チェッカーが使います。例えば:
class C: def meth(self) -> int: return 0 def func(x: Proto) -> int: return x.meth() func(C()) # Passes static type check
詳細については PEP 544 を参照してください。
runtime_checkable()(後で説明します) でデコレートされたプロトコルクラスは、与えられたメソッドがあることだけを確認し、その型シグネチャは全く見ない安直な動作をする実行時プロトコルとして振る舞います。プロトコルクラスはジェネリックにもできます。例えば:
class GenProto(Protocol[T]): def meth(self) -> T: ...
バージョン 3.8 で追加.
-
@typing.runtime_checkable¶ Mark a protocol class as a runtime protocol.
Such a protocol can be used with
isinstance()andissubclass(). This raisesTypeErrorwhen applied to a non-protocol class. This allows a simple-minded structural check, very similar to "one trick ponies" incollections.abcsuch asIterable. For example:@runtime_checkable class Closable(Protocol): def close(self): ... assert isinstance(open('/some/file'), Closable) @runtime_checkable class Named(Protocol): name: str import threading assert isinstance(threading.Thread(name='Bob'), Named)
注釈
runtime_checkable()will check only the presence of the required methods or attributes, not their type signatures or types. For example,ssl.SSLObjectis a class, therefore it passes anissubclass()check againstCallable. However, thessl.SSLObject.__init__method exists only to raise aTypeErrorwith a more informative message, therefore making it impossible to call (instantiate)ssl.SSLObject.注釈
An
isinstance()check against a runtime-checkable protocol can be surprisingly slow compared to anisinstance()check against a non-protocol class. Consider using alternative idioms such ashasattr()calls for structural checks in performance-sensitive code.バージョン 3.8 で追加.
Other special directives¶
These are not used in annotations. They are building blocks for declaring types.
-
class
typing.NamedTuple¶ collections.namedtuple()の型付き版です。使い方:
class Employee(NamedTuple): name: str id: int
これは次と等価です:
Employee = collections.namedtuple('Employee', ['name', 'id'])
フィールドにデフォルト値を与えるにはクラス本体で代入してください:
class Employee(NamedTuple): name: str id: int = 3 employee = Employee('Guido') assert employee.id == 3
デフォルト値のあるフィールドはデフォルト値のないフィールドの後でなければなりません。
最終的に出来上がるクラスには、フィールド名をフィールド型へ対応付ける辞書を提供する
__annotations__属性が追加されています。 (フィールド名は_fields属性に、デフォルト値は_field_defaults属性に格納されていて、両方ともnamedtuple()API の一部分です。)NamedTupleのサブクラスは docstring やメソッドも持てます:class Employee(NamedTuple): """Represents an employee.""" name: str id: int = 3 def __repr__(self) -> str: return f'<Employee {self.name}, id={self.id}>'
後方互換な使用法:
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
バージョン 3.6 で変更: PEP 526 変数アノテーションのシンタックスが追加されました。
バージョン 3.6.1 で変更: デフォルト値、メソッド、ドキュメンテーション文字列への対応が追加されました。
バージョン 3.8 で変更:
_field_types属性および__annotations__属性はOrderedDictインスタンスではなく普通の辞書になりました。バージョン 3.9 で変更:
_field_types属性は削除されました。代わりに同じ情報を持つより標準的な__annotations__属性を使ってください。
-
class
typing.NewType(name, tp)¶ A helper class to indicate a distinct type to a typechecker, see NewType. At runtime it returns an object that returns its argument when called. Usage:
UserId = NewType('UserId', int) first_user = UserId(1)
バージョン 3.5.2 で追加.
バージョン 3.10 で変更:
NewTypeis now a class rather than a function.
-
class
typing.TypedDict(dict)¶ Special construct to add type hints to a dictionary. At runtime it is a plain
dict.TypedDictは、その全てのインスタンスにおいてキーの集合が固定されていて、各キーに対応する値が全てのインスタンスで同じ型を持つことが期待される辞書型を宣言します。 この期待は実行時にはチェックされず、型チェッカーでのみ強制されます。 使用方法は次の通りです:class Point2D(TypedDict): x: int y: int label: str a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
To allow using this feature with older versions of Python that do not support PEP 526,
TypedDictsupports two additional equivalent syntactic forms:Point2D = TypedDict('Point2D', x=int, y=int, label=str) Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
The functional syntax should also be used when any of the keys are not valid identifiers, for example because they are keywords or contain hyphens. Example:
# raises SyntaxError class Point2D(TypedDict): in: int # 'in' is a keyword x-y: int # name with hyphens # OK, functional syntax Point2D = TypedDict('Point2D', {'in': int, 'x-y': int})
By default, all keys must be present in a
TypedDict. It is possible to override this by specifying totality. Usage:class Point2D(TypedDict, total=False): x: int y: int
This means that a
Point2DTypedDictcan have any of the keys omitted. A type checker is only expected to support a literalFalseorTrueas the value of thetotalargument.Trueis the default, and makes all items defined in the class body required.It is possible for a
TypedDicttype to inherit from one or more otherTypedDicttypes using the class-based syntax. Usage:class Point3D(Point2D): z: int
Point3Dhas three items:x,yandz. It is equivalent to this definition:class Point3D(TypedDict): x: int y: int z: int
A
TypedDictcannot inherit from a non-TypedDictclass, notably includingGeneric. For example:class X(TypedDict): x: int class Y(TypedDict): y: int class Z(object): pass # A non-TypedDict class class XY(X, Y): pass # OK class XZ(X, Z): pass # raises TypeError T = TypeVar('T') class XT(X, Generic[T]): pass # raises TypeError
A
TypedDictcan be introspected via annotations dicts (see Annotations Best Practices for more information on annotations best practices),__total__,__required_keys__, and__optional_keys__.-
__total__¶ Point2D.__total__gives the value of thetotalargument. Example:>>> from typing import TypedDict >>> class Point2D(TypedDict): pass >>> Point2D.__total__ True >>> class Point2D(TypedDict, total=False): pass >>> Point2D.__total__ False >>> class Point3D(Point2D): pass >>> Point3D.__total__ True
-
__required_keys__¶ バージョン 3.9 で追加.
-
__optional_keys__¶ Point2D.__required_keys__andPoint2D.__optional_keys__returnfrozensetobjects containing required and non-required keys, respectively. Currently the only way to declare both required and non-required keys in the sameTypedDictis mixed inheritance, declaring aTypedDictwith one value for thetotalargument and then inheriting it from anotherTypedDictwith a different value fortotal. Usage:>>> class Point2D(TypedDict, total=False): ... x: int ... y: int ... >>> class Point3D(Point2D): ... z: int ... >>> Point3D.__required_keys__ == frozenset({'z'}) True >>> Point3D.__optional_keys__ == frozenset({'x', 'y'}) True
バージョン 3.9 で追加.
他の例や、
TypedDictを扱う詳細な規則については PEP 589 を参照してください。バージョン 3.8 で追加.
-
Generic concrete collections¶
Corresponding to built-in types¶
-
class
typing.Dict(dict, MutableMapping[KT, VT])¶ dictのジェネリック版です。 返り値の型のアノテーションをつけることに便利です。 引数にアノテーションをつけるためには、Mappingのような抽象コレクション型を使うことが好ましいです。この型は次のように使えます:
def count_words(text: str) -> Dict[str, int]: ...
バージョン 3.9 で非推奨:
builtins.dictは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.List(list, MutableSequence[T])¶ listのジェネリック版です。 返り値の型のアノテーションをつけるのに便利です。 引数にアノテーションをつけるためには、SequenceやIterableのような抽象コレクション型を使うことが好ましいです。この型は次のように使えます:
T = TypeVar('T', int, float) def vec2(x: T, y: T) -> List[T]: return [x, y] def keep_positives(vector: Sequence[T]) -> List[T]: return [item for item in vector if item > 0]
バージョン 3.9 で非推奨:
builtins.listは添字表記 ([]) をサポートするようになりました。PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.Set(set, MutableSet[T])¶ builtins.setのジェネリック版です。 返り値の型のアノテーションをつけるのに便利です。 引数にアノテーションをつけるためには、AbstractSetのような抽象コレクション型を使うことが好ましいです。バージョン 3.9 で非推奨:
builtins.setは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.FrozenSet(frozenset, AbstractSet[T_co])¶ builtins.frozensetのジェネリック版です。バージョン 3.9 で非推奨:
builtins.frozensetは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
注釈
Tuple is a special form.
Corresponding to types in collections¶
-
class
typing.DefaultDict(collections.defaultdict, MutableMapping[KT, VT])¶ collections.defaultdictのジェネリック版です。バージョン 3.5.2 で追加.
バージョン 3.9 で非推奨:
collections.defaultdictは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.OrderedDict(collections.OrderedDict, MutableMapping[KT, VT])¶ collections.OrderedDictのジェネリック版です。バージョン 3.7.2 で追加.
バージョン 3.9 で非推奨:
collections.OrderedDictは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.ChainMap(collections.ChainMap, MutableMapping[KT, VT])¶ collections.ChainMapのジェネリック版です。バージョン 3.5.4 で追加.
バージョン 3.6.1 で追加.
バージョン 3.9 で非推奨:
collections.ChainMapは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.Counter(collections.Counter, Dict[T, int])¶ collections.Counterのジェネリック版です。バージョン 3.5.4 で追加.
バージョン 3.6.1 で追加.
バージョン 3.9 で非推奨:
collections.Counterは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.Deque(deque, MutableSequence[T])¶ collections.dequeのジェネリック版です。バージョン 3.5.4 で追加.
バージョン 3.6.1 で追加.
バージョン 3.9 で非推奨:
collections.dequeは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
Other concrete types¶
-
class
typing.IO¶ -
class
typing.TextIO¶ -
class
typing.BinaryIO¶ ジェネリック型
IO[AnyStr]とそのサブクラスのTextIO(IO[str])およびBinaryIO(IO[bytes])は、open()関数が返すような I/O ストリームの型を表します。Deprecated since version 3.8, will be removed in version 3.13: The
typing.ionamespace is deprecated and will be removed. These types should be directly imported fromtypinginstead.
-
class
typing.Pattern¶ -
class
typing.Match¶ これらの型エイリアスは
re.compile()とre.match()の返り値の型に対応します。 これらの型 (と対応する関数) はAnyStrについてジェネリックで、Pattern[str]、Pattern[bytes]、Match[str]、Match[bytes]と書くことで具体型にできます。Deprecated since version 3.8, will be removed in version 3.13: The
typing.renamespace is deprecated and will be removed. These types should be directly imported fromtypinginstead.バージョン 3.9 で非推奨: Classes
PatternandMatchfromrenow support[]. See PEP 585 and ジェネリックエイリアス型.
-
class
typing.Text¶ Textはstrのエイリアスです。これは Python 2 のコードの前方互換性を提供するために設けられています: Python 2 ではTextはunicodeのエイリアスです。Textは Python 2 と Python 3 の両方と互換性のある方法で値が unicode 文字列を含んでいなければならない場合に使用してください。def add_unicode_checkmark(text: Text) -> Text: return text + u' \u2713'
バージョン 3.5.2 で追加.
抽象基底クラス¶
Corresponding to collections in collections.abc¶
-
class
typing.AbstractSet(Collection[T_co])¶ collections.abc.Setのジェネリック版です。バージョン 3.9 で非推奨:
collections.abc.Setは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.ByteString(Sequence[int])¶ collections.abc.ByteStringのジェネリック版です。この型は
bytesとbytearray、バイト列のmemoryviewを表します。この型の省略形として、
bytesを上に挙げた任意の型の引数にアノテーションをつけることに使えます。バージョン 3.9 で非推奨:
collections.abc.ByteStringnow supports subscripting ([]). See PEP 585 and ジェネリックエイリアス型.
-
class
typing.Collection(Sized, Iterable[T_co], Container[T_co])¶ collections.abc.Collectionのジェネリック版です。バージョン 3.6.0 で追加.
バージョン 3.9 で非推奨:
collections.abc.Collectionは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.Container(Generic[T_co])¶ collections.abc.Containerのジェネリック版です。バージョン 3.9 で非推奨:
collections.abc.Containerは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.ItemsView(MappingView, AbstractSet[tuple[KT_co, VT_co]])¶ collections.abc.ItemsViewのジェネリック版です。バージョン 3.9 で非推奨:
collections.abc.ItemsViewは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.KeysView(MappingView, AbstractSet[KT_co])¶ collections.abc.KeysViewのジェネリック版です。バージョン 3.9 で非推奨:
collections.abc.KeysViewは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.Mapping(Collection[KT], Generic[KT, VT_co])¶ collections.abc.Mappingのジェネリック版です。 この型は次のように使えます:def get_position_in_index(word_list: Mapping[str, int], word: str) -> int: return word_list[word]
バージョン 3.9 で非推奨:
collections.abc.Mappingは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.MappingView(Sized)¶ collections.abc.MappingViewのジェネリック版です。バージョン 3.9 で非推奨:
collections.abc.MappingViewは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.MutableMapping(Mapping[KT, VT])¶ collections.abc.MutableMappingのジェネリック版です。バージョン 3.9 で非推奨:
collections.abc.MutableMappingは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.MutableSequence(Sequence[T])¶ collections.abc.MutableSequenceのジェネリック版です。バージョン 3.9 で非推奨:
collections.abc.MutableSequenceは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.MutableSet(AbstractSet[T])¶ collections.abc.MutableSetのジェネリック版です。バージョン 3.9 で非推奨:
collections.abc.MutableSetは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.Sequence(Reversible[T_co], Collection[T_co])¶ collections.abc.Sequenceのジェネリック版です。バージョン 3.9 で非推奨:
collections.abc.Sequenceは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.ValuesView(MappingView, Collection[_VT_co])¶ collections.abc.ValuesViewのジェネリック版です。バージョン 3.9 で非推奨:
collections.abc.ValuesViewは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
Corresponding to other types in collections.abc¶
-
class
typing.Iterable(Generic[T_co])¶ collections.abc.Iterableのジェネリック版です。バージョン 3.9 で非推奨:
collections.abc.Iterableは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.Iterator(Iterable[T_co])¶ collections.abc.Iteratorのジェネリック版です。バージョン 3.9 で非推奨:
collections.abc.Iteratorは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.Generator(Iterator[T_co], Generic[T_co, T_contra, V_co])¶ ジェネレータはジェネリック型
Generator[YieldType, SendType, ReturnType]によってアノテーションを付けられます。例えば:def echo_round() -> Generator[int, float, str]: sent = yield 0 while sent >= 0: sent = yield round(sent) return 'Done'
typing モジュールの多くの他のジェネリクスと違い
GeneratorのSendTypeは共変や不変ではなく、反変として扱われることに注意してください。もしジェネレータが値を返すだけの場合は、
SendTypeとReturnTypeにNoneを設定してください:def infinite_stream(start: int) -> Generator[int, None, None]: while True: yield start start += 1
代わりに、ジェネレータを
Iterable[YieldType]やIterator[YieldType]という返り値の型でアノテーションをつけることもできます:def infinite_stream(start: int) -> Iterator[int]: while True: yield start start += 1
バージョン 3.9 で非推奨:
collections.abc.Generatorは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.Hashable¶ collections.abc.Hashableへのエイリアスです。
-
class
typing.Reversible(Iterable[T_co])¶ collections.abc.Reversibleのジェネリック版です。バージョン 3.9 で非推奨:
collections.abc.Reversibleは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.Sized¶ collections.abc.Sizedへのエイリアスです。
Asynchronous programming¶
-
class
typing.Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co])¶ collections.abc.Coroutineのジェネリック版です。 変性と型変数の順序はGeneratorのものと対応しています。例えば次のようになります:from collections.abc import Coroutine c: Coroutine[list[str], str, int] # Some coroutine defined elsewhere x = c.send('hi') # Inferred type of 'x' is list[str] async def bar() -> None: y = await c # Inferred type of 'y' is int
バージョン 3.5.3 で追加.
バージョン 3.9 で非推奨:
collections.abc.Coroutineは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra])¶ 非同期ジェネレータはジェネリック型
AsyncGenerator[YieldType, SendType]によってアノテーションを付けられます。例えば:async def echo_round() -> AsyncGenerator[int, float]: sent = yield 0 while sent >= 0.0: rounded = await round(sent) sent = yield rounded
通常のジェネレータと違って非同期ジェネレータは値を返せないので、
ReturnType型引数はありません。Generatorと同様に、SendTypeは反変的に振る舞います。ジェネレータが値を yield するだけなら、
SendTypeをNoneにします:async def infinite_stream(start: int) -> AsyncGenerator[int, None]: while True: yield start start = await increment(start)
あるいは、ジェネレータが
AsyncIterable[YieldType]とAsyncIterator[YieldType]のいずれかの戻り値型を持つとアノテートします:async def infinite_stream(start: int) -> AsyncIterator[int]: while True: yield start start = await increment(start)
バージョン 3.6.1 で追加.
バージョン 3.9 で非推奨:
collections.abc.AsyncGeneratorは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.AsyncIterable(Generic[T_co])¶ collections.abc.AsyncIterableのジェネリック版です。バージョン 3.5.2 で追加.
バージョン 3.9 で非推奨:
collections.abc.AsyncIterableは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.AsyncIterator(AsyncIterable[T_co])¶ collections.abc.AsyncIteratorのジェネリック版です。バージョン 3.5.2 で追加.
バージョン 3.9 で非推奨:
collections.abc.AsyncIteratorは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.Awaitable(Generic[T_co])¶ collections.abc.Awaitableのジェネリック版です。バージョン 3.5.2 で追加.
バージョン 3.9 で非推奨:
collections.abc.Awaitableは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
コンテキストマネージャ型¶
-
class
typing.ContextManager(Generic[T_co])¶ contextlib.AbstractContextManagerのジェネリック版です。バージョン 3.5.4 で追加.
バージョン 3.6.0 で追加.
バージョン 3.9 で非推奨:
contextlib.AbstractContextManagerは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
-
class
typing.AsyncContextManager(Generic[T_co])¶ contextlib.AbstractAsyncContextManagerのジェネリック版です。バージョン 3.5.4 で追加.
バージョン 3.6.2 で追加.
バージョン 3.9 で非推奨:
contextlib.AbstractAsyncContextManagerは添字表記 ([]) をサポートするようになりました。 PEP 585 と ジェネリックエイリアス型 を参照してください。
プロトコル¶
These protocols are decorated with runtime_checkable().
-
class
typing.SupportsAbs¶ 返り値の型と共変な抽象メソッド
__abs__を備えた ABC です。
-
class
typing.SupportsBytes¶ 抽象メソッド
__bytes__を備えた ABC です。
-
class
typing.SupportsComplex¶ 抽象メソッド
__complex__を備えた ABC です。
-
class
typing.SupportsFloat¶ 抽象メソッド
__float__を備えた ABC です。
-
class
typing.SupportsIndex¶ 抽象メソッド
__index__を備えた ABC です。バージョン 3.8 で追加.
-
class
typing.SupportsInt¶ 抽象メソッド
__int__を備えた ABC です。
-
class
typing.SupportsRound¶ 返り値の型と共変な抽象メソッド
__round__を備えた ABC です。
Functions and decorators¶
-
typing.cast(typ, val)¶ 値をある型にキャストします。
この関数は値を変更せずに返します。 型検査器に対して、返り値が指定された型を持っていることを通知しますが、実行時には意図的に何も検査しません。 (その理由は、処理をできる限り速くしたかったためです。)
-
@typing.overload¶ @overloadデコレータを使うと、引数の型の複数の組み合わせをサポートする関数やメソッドを書けるようになります。@overload付きの定義を並べた後ろに、(同じ関数やメソッドの)@overload無しの定義が来なければなりません。@overload付きの定義は型チェッカーのためでしかありません。 というのも、@overload付きの定義は@overload無しの定義で上書きされるからです。 後者は実行時に使われますが、型チェッカーからは無視されるべきなのです。 実行時には、@overload付きの関数を直接呼び出すとNotImplementedErrorを送出します。 次のコードはオーバーロードを使うことで直和型や型変数を使うよりもより正確な型が表現できる例です:@overload def process(response: None) -> None: ... @overload def process(response: int) -> tuple[int, str]: ... @overload def process(response: bytes) -> str: ... def process(response): <actual implementation>
詳細と他の型付け意味論との比較は PEP 484 を参照してください。
-
@typing.final¶ A decorator to indicate to type checkers that the decorated method cannot be overridden, and the decorated class cannot be subclassed. For example:
class Base: @final def done(self) -> None: ... class Sub(Base): def done(self) -> None: # Error reported by type checker ... @final class Leaf: ... class Other(Leaf): # Error reported by type checker ...
この機能は実行時には検査されません。詳細については PEP 591 を参照してください。
バージョン 3.8 で追加.
-
@typing.no_type_check¶ アノテーションが型ヒントでないことを示すデコレータです。
これはクラス decorator または関数 decorator として動作します。クラス decorator として動作する場合は、そのクラス内に定義されたすべてのメソッドに対して再帰的に適用されます。(ただしスーパークラスやサブクラス内に定義されたメソッドには適用されません。)
これは関数を適切に変更します。
-
@typing.no_type_check_decorator¶ 別のデコレータに
no_type_check()の効果を与えるデコレータです。これは何かの関数をラップするデコレータを
no_type_check()でラップします。
-
@typing.type_check_only¶ 実行時に使えなくなるクラスや関数に印を付けるデコレータです。
このデコレータ自身は実行時には使えません。 このデコレータは主に、実装がプライベートクラスのインスタンスを返す場合に、型スタブファイルに定義されているクラスに対して印を付けるためのものです:
@type_check_only class Response: # private or not available at runtime code: int def get_header(self, name: str) -> str: ... def fetch_response() -> Response: ...
プライベートクラスのインスタンスを返すのは推奨されません。 そのようなクラスは公開クラスにするのが望ましいです。
Introspection helpers¶
-
typing.get_type_hints(obj, globalns=None, localns=None, include_extras=False)¶ 関数、メソッド、モジュールまたはクラスのオブジェクトの型ヒントを含む辞書を返します。
この辞書はたいてい
obj.__annotations__と同じものです。 それに加えて、文字列リテラルにエンコードされた順方向参照はglobals名前空間およびlocals名前空間で評価されます。 必要であれば、Noneと等価なデフォルト値が設定されている場合に、関数とメソッドのアノテーションにOptional[t]が追加されます。 クラスCについては、C.__mro__の逆順に沿って全ての__annotations__を合併して構築された辞書を返します。The function recursively replaces all
Annotated[T, ...]withT, unlessinclude_extrasis set toTrue(seeAnnotatedfor more information). For example:class Student(NamedTuple): name: Annotated[str, 'some marker'] get_type_hints(Student) == {'name': str} get_type_hints(Student, include_extras=False) == {'name': str} get_type_hints(Student, include_extras=True) == { 'name': Annotated[str, 'some marker'] }
注釈
get_type_hints()does not work with imported type aliases that include forward references. Enabling postponed evaluation of annotations (PEP 563) may remove the need for most forward references.バージョン 3.9 で変更: Added
include_extrasparameter as part of PEP 593.
-
typing.get_args(tp)¶
-
typing.get_origin(tp)¶ ジェネリック型や特殊な型付け形式についての基本的な内観を提供します。
For a typing object of the form
X[Y, Z, ...]these functions returnXand(Y, Z, ...). IfXis a generic alias for a builtin orcollectionsclass, it gets normalized to the original class. IfXis a union orLiteralcontained in another generic type, the order of(Y, Z, ...)may be different from the order of the original arguments[Y, Z, ...]due to type caching. For unsupported objects returnNoneand()correspondingly. Examples:assert get_origin(Dict[str, int]) is dict assert get_args(Dict[int, str]) == (int, str) assert get_origin(Union[int, str]) is Union assert get_args(Union[int, str]) == (int, str)
バージョン 3.8 で追加.
-
typing.is_typeddict(tp)¶ Check if a type is a
TypedDict.例えば:
class Film(TypedDict): title: str year: int is_typeddict(Film) # => True is_typeddict(list | str) # => False
バージョン 3.10 で追加.
-
class
typing.ForwardRef¶ 文字列による前方参照の内部的な型付け表現に使われるクラスです。 例えば、
List["SomeClass"]は暗黙的にList[ForwardRef("SomeClass")]に変換されます。 このクラスはユーザーがインスタンス化するべきではなく、イントロスペクションツールに使われるものです。注釈
PEP 585 generic types such as
list["SomeClass"]will not be implicitly transformed intolist[ForwardRef("SomeClass")]and thus will not automatically resolve tolist[SomeClass].バージョン 3.7.4 で追加.
定数¶
-
typing.TYPE_CHECKING¶ サードパーティーの静的型検査器が
Trueと仮定する特別な定数です。 実行時にはFalseになります。使用例:if TYPE_CHECKING: import expensive_mod def fun(arg: 'expensive_mod.SomeType') -> None: local_var: expensive_mod.AnotherType = other_fun()
The first type annotation must be enclosed in quotes, making it a "forward reference", to hide the
expensive_modreference from the interpreter runtime. Type annotations for local variables are not evaluated, so the second annotation does not need to be enclosed in quotes.注釈
from __future__ import annotationsが使われた場合、アノーテーションは関数定義時に評価されません。代わりにアノーテーションは__annotations__属性に文字列として保存されます。これによりアノーテーションをシングルクォートで囲む必要がなくなります (PEP 563 を参照してください)。バージョン 3.5.2 で追加.