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

バージョン 3.5 で追加.

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

注釈:

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

======================================================================

This module provides runtime support for type hints. The most
fundamental support consists of the types "Any", "Union", "Callable",
"TypeVar", and "Generic". For a full specification, please see **PEP
484**. For a simplified introduction to type hints, see **PEP 483**.

以下の関数は文字列を受け取って文字列を返す関数で、次のようにアノテーシ
ョンがつけられます:

   def greeting(name: str) -> str:
       return 'Hello ' + name

関数 "greeting" で、実引数 "name" の型は "str" であり、返り値の型は
"str" であることが期待されます。サブタイプも実引数として許容されます。

New features are frequently added to the "typing" module. The
typing_extensions package provides backports of these new features to
older versions of Python.


Relevant PEPs
=============

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 526**: Syntax for Variable Annotations
     *Introducing* syntax for annotating variables outside of function
     definitions, and "ClassVar"

* **PEP 544**: Protocols: Structural subtyping (static duck typing)
     *Introducing* "Protocol" and the "@runtime_checkable" decorator

* **PEP 585**: Type Hinting Generics In Standard Collections
     *Introducing* "types.GenericAlias" and the ability to use
     standard library classes as generic types

* **PEP 586**: Literal Types
     *Introducing* "Literal"

* **PEP 589**: TypedDict: Type Hints for Dictionaries with a Fixed Set
  of Keys
     *Introducing* "TypedDict"

* **PEP 591**: Adding a final qualifier to typing
     *Introducing* "Final" and the "@final" decorator

* **PEP 593**: Flexible function and variable annotations
     *Introducing* "Annotated"


型エイリアス
============

型エイリアスは、型をエイリアスに割り当てて定義されます。 この例では、
"Vector" と "list[float]" が置き換え可能な同義語として扱われます:

   Vector = list[float]

   def scale(scalar: float, vector: Vector) -> Vector:
       return [scalar * num for num in vector]

   # typechecks; 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
=======

Use the "NewType()" helper to create distinct types:

   from typing import NewType

   UserId = NewType('UserId', int)
   some_id = UserId(524313)

静的型検査器は新しい型を元々の型のサブクラスのように扱います。この振る
舞いは論理的な誤りを見つける手助けとして役に立ちます。

   def get_user_name(user_id: UserId) -> str:
       ...

   # typechecks
   user_a = get_user_name(UserId(42351))

   # does not typecheck; 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)

Note that these checks are enforced only by the static type checker.
At runtime, the statement "Derived = NewType('Derived', Base)" will
make "Derived" a callable that immediately returns whatever parameter
you pass it. That means the expression "Derived(some_value)" does not
create a new class or introduce any overhead beyond that of a regular
function call.

より正確に言うと、式 "some_value is Derived(some_value)" は実行時に常
に真を返します。

これは "Derived" のサブタイプを作ることが出来ないということも意味して
います。 "Derived" は実行時には恒等関数になっていて、実際の型ではない
からです:

   from typing import NewType

   UserId = NewType('UserId', int)

   # Fails at runtime and does not typecheck
   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 で追加.


呼び出し可能オブジェクト
========================

特定のシグネチャを持つコールバック関数を要求されるフレームワークでは、
"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]"。


ジェネリクス
============

コンテナ内のオブジェクトについての型情報は一般的な方法では静的に推論で
きないため、抽象基底クラスを継承したクラスが実装され、期待されるコンテ
ナの要素の型を示すために添字表記をサポートするようになりました。

   from collections.abc import Mapping, Sequence

   def notify_by_email(employees: Sequence[Employee],
                       overrides: Mapping[str, str]) -> None: ...

Generics can be parameterized by using a factory available in typing
called "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" が型として有効になります。

The "Generic" base class defines "__class_getitem__()" so that
"LoggedVar[t]" is valid as a type:

   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, Union
   S = TypeVar('S')
   Response = Union[Iterable[S], int]

   # Return type here is same as Union[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" にあった独自のメタクラスは無くなりま
した。

ユーザーが定義したジェネリッククラスはメタクラスの衝突を起こすことなく
基底クラスに抽象基底クラスをとれます。 ジェネリックメタクラスはサポー
トされません。 パラメータ化を行うジェネリクスの結果はキャッシュされて
いて、 typing モジュールのほとんどの型はハッシュ化でき、等価比較できま
す。


"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:
       # Typechecks; '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; an object does not have a 'magic' method.
       item.magic()
       ...

   def hash_b(item: Any) -> int:
       # Typechecks
       item.magic()
       ...

   # Typechecks, since ints and strs are subclasses of object
   hash_a(42)
   hash_a("foo")

   # Typechecks, since Any is compatible with all types
   hash_b(42)
   hash_b("foo")

"object" は、ある値が型安全な方法で任意の型として使えることを示すため
に使用します。 "Any" はある値が動的に型付けられることを示すために使用
します。


名前的部分型 vs 構造的部分型
============================

Initially **PEP 484** defined the Python static type system as using
*nominal subtyping*. This means that a class "A" is allowed where a
class "B" is expected if and only if "A" is a subclass of "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.Any

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

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

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

typing.NoReturn

   関数が返り値を持たないことを示す特別な型です。例えば次のように使い
   ます:

      from typing import NoReturn

      def stop() -> NoReturn:
          raise RuntimeError('no way')

   バージョン 3.5.4 で追加.

   バージョン 3.6.2 で追加.


特殊形式
~~~~~~~~

これらは "[]" を使ったアノテーションの内部の型として使え、それぞれ固有
の文法があります。

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 を表します。

   ユニオン型を定義します、例えば "Union[int, str]" のように使います。
   詳細:

   * 引数は型でなければならず、少なくとも一つ必要です。

   * ユニオン型のユニオン型は平滑化されます。例えば:

        Union[Union[int, str], float] == Union[int, str, float]

   * 引数が一つのユニオン型は消えます。例えば:

        Union[int] == int  # The constructor actually returns int

   * 冗長な実引数は飛ばされます。例えば:

        Union[int, str, int] == Union[int, str]

   * ユニオン型を比較するとき引数の順序は無視されます。例えば:

        Union[int, str] == Union[str, int]

   * ユニオン型のサブクラスを作成したり、インスタンスを作成することは
     出来ません。

   * "Union[X][Y]" と書くことは出来ません。

   * "Optional[X]" を "Union[X, None]" の略記として利用することが出来
     ます。

   バージョン 3.7 で変更: 明示的に書かれているサブクラスを、実行時に直
   和型から取り除かなくなりました。

typing.Optional

   オプショナル型。

   "Optional[X]" は "Union[X, None]" と同値です。

   これがデフォルト値を持つオプション引数とは同じ概念ではないというこ
   とに注意してください。 デフォルト値を持つオプション引数はオプション
   引数であるために、型アノテーションに "Optional" 修飾子は必要ありま
   せん。 例えば次のようになります:

      def foo(arg: int = 0) -> None:
          ...

   それとは逆に、 "None" という値が許されていることが明示されている場
   合は、引数がオプションであろうとなかろうと、 "Optional" を使うのが
   好ましいです。 例えば次のようになります:

      def foo(arg: Optional[int] = None) -> None:
          ...

typing.Callable

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

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

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

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

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[Union[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 で追加.

   バージョン 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

   A type, introduced in **PEP 593** ("Flexible function and variable
   annotations"), to decorate existing types with context-specific
   metadata (possibly multiple pieces of it, as "Annotated" is
   variadic). Specifically, a type "T" can be annotated with metadata
   "x" via the typehint "Annotated[T, x]". This metadata can be used
   for either static analysis or at runtime. If a library (or tool)
   encounters a typehint "Annotated[T, x]" and has no special logic
   for metadata "x", it should ignore it and simply treat the type as
   "T". Unlike the "no_type_check" functionality that currently exists
   in the "typing" module which completely disables typechecking
   annotations on a function or a class, the "Annotated" type allows
   for both static typechecking of "T" (which can safely ignore "x")
   together with runtime access to "x" within a specific application.

   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 で追加.


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 (© 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.

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()" will check only the presence of the
     required methods, not their type signatures! For example,
     "builtins.complex" implements "__float__()", therefore it passes
     an "issubclass()" check against "SupportsFloat". However, the
     "complex.__float__" method exists only to raise a "TypeError"
     with a more informative message.

   バージョン 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

   デフォルト値のあるフィールドはデフォルト値のないフィールドの後でな
   ければなりません。

   The resulting class has an extra attribute "__annotations__" giving
   a dict that maps the field names to the field types.  (The field
   names are in the "_fields" attribute and the default values are in
   the "_field_defaults" attribute, both of which are part of the
   "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__" 属性を使ってください
   。

typing.NewType(name, tp)

   異なる型であることを型チェッカーに教えるためのヘルパー関数です。
   NewType を参照してください。 実行時には、その引数を返す関数を返しま
   す。 使い方は次のようになります:

      UserId = NewType('UserId', int)
      first_user = UserId(1)

   バージョン 3.5.2 で追加.

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:

   * Using a literal "dict" as the second argument:

        Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})

   * Using keyword arguments:

        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

      # Alternative syntax
      Point2D = TypedDict('Point2D', {'x': int, 'y': int}, total=False)

   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__",
   "__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__

   __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

   他の例や、 "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.12:
   These types are also in the "typing.io" namespace, which was never
   supported by type checkers and will be removed.

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.12:
   These types are also in the "typing.re" namespace, which was never
   supported by type checkers and will be removed.

   バージョン 3.9 で非推奨: Classes "Pattern" and "Match" from "re"
   now 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(Sized, 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.ByteString" は "[]" をサ
   ポートするようになりました。 **PEP 585** および ジェネリックエイリ
   アス型 を参照してください。

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, Generic[KT_co, VT_co])

   "collections.abc.ItemsView" のジェネリック版です。

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

class typing.KeysView(MappingView[KT_co], AbstractSet[KT_co])

   "collections.abc.KeysView" のジェネリック版です。

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

class typing.Mapping(Sized, Collection[KT], Generic[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, Iterable[T_co])

   "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[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

   An alias to "collections.abc.Hashable".

class typing.Reversible(Iterable[T_co])

   "collections.abc.Reversible" のジェネリック版です。

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

class typing.Sized

   An alias to "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"
   now supports "[]". See **PEP 585** and ジェネリックエイリアス型.


プロトコル
----------

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']
      }

   バージョン 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 で追加.

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.

   注釈:

     If "from __future__ import annotations" is used, annotations are
     not evaluated at function definition time. Instead, they are
     stored as strings in "__annotations__". This makes it unnecessary
     to use quotes around the annotation (see **PEP 563**).

   バージョン 3.5.2 で追加.
