typing --- 型ヒントのサポート

バージョン 3.5 で追加.

ソースコード: Lib/typing.py

注釈

Python ランタイムは、関数や変数の型アノテーションを強制しません。型アノテーションは、型チェッカー、IDE、linterなどのサードパーティーツールで使われます。


このモジュールは型のランタイムへのサポートを提供します。最も基本的な型として:data:AnyUnionCallableTypeVarGeneric が存在します。詳細な仕様は: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:

型エイリアス

型エイリアスは、型をエイリアスに割り当てて定義されます。 この例では、Vectorlist[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) とすると静的型検査器は DerivedOriginalサブクラス として扱います。つまり 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]

Callables which take other callables as arguments may indicate that their parameter types are dependent on each other using ParamSpec. Additionally, if that callable adds or removes arguments from other callables, the Concatenate operator may be used. They take the form Callable[ParamSpecVariable, ReturnType] and Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType] respectively.

バージョン 3.10 で変更: ``Callable``は:class:`ParamSpec`と:data:`Concatenate`をサポートしました。:pep:`612`を参照してください。

参考

ParamSpec と:class: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 型の値をより詳細な型に代入する時に型検査が行われないことに注意してください。例えば、静的型検査器は as に代入する時、sstr 型として宣言されていて実行時に 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 が許容されるのは AB のサブクラスの場合かつその場合に限る、ということです。

前出の必要条件は、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 によって上にあるようなクラス定義で基底クラスを明示しないコードをユーザーが書け、静的型チェッカーで BucketSizedIterable[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 585Type Hinting Generics In Standard Collections を参照してください。

特殊型付けプリミティブ

特殊型

これらはアノテーションの内部の型として使えますが、[] はサポートしていません。

typing.Any

制約のない型であることを示す特別な型です。

  • 任意の型は Any と互換です。

  • Any は任意の型と互換です。

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, ...]。ただの TupleTuple[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 shorthand int | 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`` のように書けるようになりました。<types-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``のように書けるようになりました。<types-union>を参照ください。

typing.Callable

呼び出し可能型; Callable[[int], str] は (int) -> str の関数です。

添字表記は常に2つの値とともに使われなければなりません: 実引数のリストと返り値の型です。 実引数のリストは型のリストか ellipsis でなければなりません; 返り値の型は単一の型でなければなりません。

オプショナル引数やキーワード引数を表すための文法はありません; そのような関数型はコールバックの型として滅多に使われません。 Callable[..., ReturnType] (リテラルの Ellipsis) は任意の個数の引数をとり ReturnType を返す型ヒントを与えるために使えます。 普通の CallableCallable[..., Any] と同等で、 collections.abc.Callable でも同様です。

Callables which take other callables as arguments may indicate that their parameter types are dependent on each other using ParamSpec. Additionally, if that callable adds or removes arguments from other callables, the Concatenate operator may be used. They take the form Callable[ParamSpecVariable, ReturnType] and Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType] respectively.

バージョン 3.9 で非推奨: collections.abc.Callable は添字表記 ([]) をサポートするようになりました。 PEP 585ジェネリックエイリアス型 を参照してください。

バージョン 3.10 で変更: ``Callable``は:class:`ParamSpec`と:data:`Concatenate`をサポートしました。:pep:`612`を参照してください。

参考

The documentation for ParamSpec and Concatenate provide examples of usage with Callable.

typing.Concatenate

Used with Callable and ParamSpec to type annotate a higher order callable which adds, removes, or transforms parameters of another callable. Usage is in the form Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable]. Concatenate is currently only valid when used as the first argument to a Callable. The last parameter to Concatenate must be a ParamSpec.

For example, to annotate a decorator with_lock which provides a threading.Lock to the decorated function, Concatenate can be used to indicate that with_lock expects a callable which takes in a Lock as the first argument, and returns a callable with a different type signature. In this case, the ParamSpec indicates 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 で追加.

参考

  • PEP 612 -- Parameter Specification Variables (the PEP which introduced ParamSpec and Concatenate).

  • ParamSpec and Callable.

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 と等価で、同様に Typetype と等価です。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 で追加.

バージョン 3.9.1 で変更: Literal ではパラメータの重複を解消するようになりました。Literal オブジェクトの等値比較は順序に依存しないようになりました。Literal オブジェクトは、等値比較する際に、パラメータのうち 1 つでも hashable でない場合は TypeError を送出するようになりました。

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 になるメタデータの複数の破片) を持つ既存の型を装飾します。 具体的には、型 TAnnotated[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 Annotated type. A tool or library encountering an Annotated type can scan through the annotations to determine if they are of interest (e.g., using isinstance()).

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 Annotated type 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=True to get_type_hints() lets one access the extra annotations at runtime.

The details of the syntax:

  • The first argument to Annotated must be a valid type

  • Multiple type annotations are supported (Annotated supports variadic arguments):

    Annotated[int, ValueRange(3, 10), ctype("char")]
    
  • Annotated must 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 Annotated types 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)
    ]
    
  • Annotated can 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. TypeGuard only accepts a single type argument. At runtime, functions marked this way should return a boolean.

TypeGuard aims 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 -> TypeGuard tells the static type checker that for a given function:

  1. The return value is a boolean.

  2. If the return value is True, the type of its argument is the type inside TypeGuard.

例えば:

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_list is a class or instance method, then the type in TypeGuard maps to the type of the second parameter after cls or self.

In short, the form def foo(arg: TypeA) -> TypeGuard[TypeB]: ..., means that if foo(arg) returns True, then arg narrows from TypeA to TypeB.

注釈

TypeB need not be a narrower form of TypeA -- it can even be a wider form. The main reason is to allow for things like narrowing List[object] to List[str] even though the latter is not a subtype of the former, since List is invariant. The responsibility of writing type-safe type guards is left to the user.

TypeGuard also 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 TypeVar can 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 TypeVar will 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 classmethods that serve as alternative constructors. In the following example (by Raymond Hettinger), the type variable C is bound to the Circle class through the use of a forward reference. Using this type variable to annotate the with_circumference classmethod, rather than hardcoding the return type as Circle, 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=True or contravariant=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 to Callable, or as parameters for user-defined Generics. See Generic for more information on generic types.

For example, to add basic logging to a function, one can create a decorator add_logging to 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 a TypeVar with bound Callable[..., Any]. However this causes two problems:

  1. The type checker can't type check the inner function because *args and **kwargs have to be typed Any.

  2. cast() may be required in the body of the add_logging decorator when returning the inner function, or the static type checker must be told to ignore the return inner.

args
kwargs

Since ParamSpec captures both positional and keyword parameters, P.args and P.kwargs can be used to split a ParamSpec into its components. P.args represents the tuple of positional parameters in a given call and should only be used to annotate *args. P.kwargs represents 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.args and P.kwargs are instances respectively of ParamSpecArgs and ParamSpecKwargs.

Parameter specification variables created with covariant=True or contravariant=True can be used to declare covariant or contravariant generic types. The bound argument is also accepted, similar to TypeVar. 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.

参考

typing.ParamSpecArgs
typing.ParamSpecKwargs

Arguments and keyword arguments attributes of a ParamSpec. The P.args attribute of a ParamSpec is an instance of ParamSpecArgs, and P.kwargs is an instance of ParamSpecKwargs. 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 original ParamSpec:

P = ParamSpec("P")
get_origin(P.args)  # returns P
get_origin(P.kwargs)  # returns P

バージョン 3.10 で追加.

typing.AnyStr

AnyStr is a constrained type variable defined as AnyStr = 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() and issubclass(). This raises TypeError when applied to a non-protocol class. This allows a simple-minded structural check, very similar to "one trick ponies" in collections.abc such as Iterable. 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.SSLObject is a class, therefore it passes an issubclass() check against Callable. However, the ssl.SSLObject.__init__ method exists only to raise a TypeError with 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 an isinstance() check against a non-protocol class. Consider using alternative idioms such as hasattr() 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 で変更: NewType is 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, TypedDict supports 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 Point2D TypedDict can have any of the keys omitted. A type checker is only expected to support a literal False or True as the value of the total argument. True is the default, and makes all items defined in the class body required.

It is possible for a TypedDict type to inherit from one or more other TypedDict types using the class-based syntax. Usage:

class Point3D(Point2D):
    z: int

Point3D has three items: x, y and z. It is equivalent to this definition:

class Point3D(TypedDict):
    x: int
    y: int
    z: int

A TypedDict cannot inherit from a non-TypedDict class, notably including Generic. 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 TypedDict can 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 the total argument. 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__ and Point2D.__optional_keys__ return frozenset objects containing required and non-required keys, respectively. Currently the only way to declare both required and non-required keys in the same TypedDict is mixed inheritance, declaring a TypedDict with one value for the total argument and then inheriting it from another TypedDict with a different value for total. 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 のジェネリック版です。 返り値の型のアノテーションをつけるのに便利です。 引数にアノテーションをつけるためには、 SequenceIterable のような抽象コレクション型を使うことが好ましいです。

この型は次のように使えます:

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 ストリームの型を表します。

バージョン 3.8 で非推奨、バージョン 3.13 で削除予定: The typing.io namespace is deprecated and will be removed. These types should be directly imported from typing instead.

class typing.Pattern
class typing.Match

これらの型エイリアスは re.compile()re.match() の返り値の型に対応します。 これらの型 (と対応する関数) は AnyStr についてジェネリックで、Pattern[str]Pattern[bytes]Match[str]Match[bytes] と書くことで具体型にできます。

バージョン 3.8 で非推奨、バージョン 3.13 で削除予定: The typing.re namespace is deprecated and will be removed. These types should be directly imported from typing instead.

バージョン 3.9 で非推奨: Classes Pattern and Match from re now support []. See PEP 585 and ジェネリックエイリアス型.

class typing.Text

Textstr のエイリアスです。これは Python 2 のコードの前方互換性を提供するために設けられています: Python 2 では Textunicode のエイリアスです。

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 のジェネリック版です。

この型は bytesbytearray 、バイト列の memoryview を表します。

この型の省略形として、 bytes を上に挙げた任意の型の引数にアノテーションをつけることに使えます。

バージョン 3.9 で非推奨: collections.abc.ByteString now 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 モジュールの多くの他のジェネリクスと違い GeneratorSendType は共変や不変ではなく、反変として扱われることに注意してください。

もしジェネレータが値を返すだけの場合は、 SendTypeReturnTypeNone を設定してください:

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 するだけなら、SendTypeNone にします:

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, ...] with T, unless include_extras is set to True (see Annotated for 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_extras parameter 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 return X and (Y, Z, ...). If X is a generic alias for a builtin or collections class, it gets normalized to the original class. If X is a union or Literal contained 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 return None and () 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 into list[ForwardRef("SomeClass")] and thus will not automatically resolve to list[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_mod reference 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 で追加.