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

バージョン 3.5 で追加.

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

注釈

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


このモジュールは型のランタイムへのサポートを提供します。最も基本的な型として:data:AnyUnionCallableTypeVarGeneric が存在します。詳細な仕様は:pep:`484`に記載があります。型ヒントの導入についての説明は:pep:`483`に記載があります。

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

defgreeting(name:str)->str:return'Hello '+name

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

typing モジュールには新しい機能が頻繁に追加されています。typing_extensions パッケージは、古いバージョンの Python への新しい機能のバックポートを提供しています。

参考

For a quick overview of type hints, refer tothis cheat sheet.

The "Type System Reference" section ofhttps://mypy.readthedocs.io/ -- sincethe Python typing system is standardised via PEPs, this reference shouldbroadly apply to most Python type checkers, although some parts may still bespecific to mypy.

The documentation athttps://typing.readthedocs.io/ serves as useful referencefor type system features, useful typing related tools and typing best practices.

関連する PEP

Since the initial introduction of type hints inPEP 484 andPEP 483, anumber of PEPs have modified and enhanced Python's framework for typeannotations. These include:

型エイリアス

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

Vector=list[float]defscale(scalar:float,vector:Vector)->Vector:return[scalar*numfornuminvector]# passes type checking; a list of floats qualifies as a Vector.new_vector=scale(2.0,[1.0,-4.2,5.4])

型エイリアスは複雑な型シグネチャを単純化するのに有用です。例えば:

fromcollections.abcimportSequenceConnectionOptions=dict[str,str]Address=tuple[str,int]Server=tuple[Address,ConnectionOptions]defbroadcast_message(message:str,servers:Sequence[Server])->None:...# The static type checker will treat the previous type signature as# being exactly equivalent to this one.defbroadcast_message(message:str,servers:Sequence[tuple[tuple[str,int],dict[str,str]]])->None:...

型ヒントとしてのNone は特別なケースであり、type(None) によって置き換えられます。

NewType

異なる型を作るためにはNewType ヘルパークラスを使います:

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

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

defget_user_name(user_id:UserId)->str:...# passes type checkinguser_a=get_user_name(UserId(42351))# fails type checking; an int is not a UserIduser_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_valueisDerived(some_value) は実行時に常に真を返します。

Derived のサブタイプを作成することはできません

fromtypingimportNewTypeUserId=NewType('UserId',int)# Fails at runtime and does not pass type checkingclassAdminUserId(UserId):pass

しかし、 'derived' であるNewType をもとにしたNewType は作ることが出来ます:

fromtypingimportNewTypeUserId=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 additionalruntime cost when callingNewType over a regular function. However, thiscost will be reduced in 3.11.0.

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

特定のシグネチャを持つコールバック関数を要求されるフレームワークでは、Callable[[Arg1Type,Arg2Type],ReturnType] を使って型ヒントを付けます。

例えば:

fromcollections.abcimportCallabledeffeeder(get_next_item:Callable[[],str])->None:# Bodydefasync_query(on_success:Callable[[int],None],on_error:Callable[[int,Exception],None])->None:# Bodyasyncdefon_update(value:str)->None:# Bodycallback:Callable[[str],Awaitable[None]]=on_update

型ヒントの実引数の型を ellipsis で置き換えることで呼び出しシグニチャを指定せずに callable の戻り値の型を宣言することができます:Callable[...,ReturnType]

callable が別の callable を引数に取る場合は、ParamSpec を使えば両者のパラメータ引数の依存関係を表現することができます。さらに、ある callable が別の callable から引数を追加したり削除したりする場合は、Concatenate 演算子を使うことで表現できます。その場合、callable の型はCallable[ParamSpecVariable,ReturnType]Callable[Concatenate[Arg1Type,Arg2Type,...,ParamSpecVariable],ReturnType] という形になります。

バージョン 3.10 で変更:CallableParamSpecConcatenate をサポートしました。詳細はPEP 612 を参照してください。

参考

ParamSpecConcatenate のドキュメントに、Callable での使用例が記載されています。

ジェネリクス

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

fromcollections.abcimportMapping,Sequencedefnotify_by_email(employees:Sequence[Employee],overrides:Mapping[str,str])->None:...

ジェネリクスは、 typing にあるTypeVar と呼ばれるファクトリを使ってパラメータ化することができます。

fromcollections.abcimportSequencefromtypingimportTypeVarT=TypeVar('T')# Declare type variabledeffirst(l:Sequence[T])->T:# Generic functionreturnl[0]

ユーザー定義のジェネリック型

ユーザー定義のクラスを、ジェネリッククラスとして定義できます。

fromtypingimportTypeVar,GenericfromloggingimportLoggerT=TypeVar('T')classLoggedVar(Generic[T]):def__init__(self,value:T,name:str,logger:Logger)->None:self.name=nameself.logger=loggerself.value=valuedefset(self,new:T)->None:self.log('Set '+repr(self.value))self.value=newdefget(self)->T:self.log('Get '+repr(self.value))returnself.valuedeflog(self,message:str)->None:self.logger.info('%s:%s',self.name,message)

Generic[T] を基底クラスにすることで、LoggedVar クラスが 1 つの型引数T をとる、と定義できます。この定義により、クラスの本体の中でもT が型として有効になります。

Generic 基底クラスはLoggedVar[T] が型として有効になるように__class_getitem__() メソッドを定義しています:

fromcollections.abcimportIterabledefzero_all_vars(vars:Iterable[LoggedVar[int]])->None:forvarinvars:var.set(0)

A generic type can have any number of type variables. All varieties ofTypeVar are permissible as parameters for a generic type:

fromtypingimportTypeVar,Generic,SequenceT=TypeVar('T',contravariant=True)B=TypeVar('B',bound=Sequence[bytes],covariant=True)S=TypeVar('S',int,str)classWeirdTrio(Generic[T,B,S]):...

Generic の引数のそれぞれの型変数は別のものでなければなりません。このため次のクラス定義は無効です:

fromtypingimportTypeVar,Generic...T=TypeVar('T')classPair(Generic[T,T]):# INVALID...

Generic を用いて多重継承が可能です:

fromcollections.abcimportSizedfromtypingimportTypeVar,GenericT=TypeVar('T')classLinkedList(Sized,Generic[T]):...

ジェネリッククラスを継承するとき、いくつかの型変数を固定することが出来ます:

fromcollections.abcimportMappingfromtypingimportTypeVarT=TypeVar('T')classMyDict(Mapping[str,T]):...

この場合ではMyDict は仮引数T を 1 つとります。

型引数を指定せずにジェネリッククラスを使う場合、それぞれの型引数にAny を与えられたものとして扱います。次の例では、MyIterable はジェネリックではありませんがIterable[Any] を暗黙的に継承しています:

fromcollections.abcimportIterableclassMyIterable(Iterable):# Same as Iterable[Any]

ユーザ定義のジェネリック型エイリアスもサポートされています。例:

fromcollections.abcimportIterablefromtypingimportTypeVarS=TypeVar('S')Response=Iterable[S]|int# Return type here is same as Iterable[str] | intdefresponse(query:str)->Response[str]:...T=TypeVar('T',int,float,complex)Vec=Iterable[tuple[T,T]]definproduct(v:Vec[T])->T:# Same as Iterable[tuple[T, T]]returnsum(x*yforx,yinv)

バージョン 3.7 で変更:Generic にあった独自のメタクラスは無くなりました。

User-defined generics for parameter expressions are also supported via parameterspecification variables in the formGeneric[P]. The behavior is consistentwith type variables' described above as parameter specification variables aretreated by the typing module as a specialized type variable. The one exceptionto this is that a list of types can be used to substitute aParamSpec:

>>>fromtypingimportGeneric,ParamSpec,TypeVar>>>T=TypeVar('T')>>>P=ParamSpec('P')>>>classZ(Generic[T,P]):......>>>Z[int,[dict,float]]__main__.Z[int, (<class 'dict'>, <class 'float'>)]

Furthermore, a generic with only one parameter specification variable will acceptparameter lists in the formsX[[Type1,Type2,...]] and alsoX[Type1,Type2,...] for aesthetic reasons. Internally, the latter is convertedto the former, so the following are equivalent:

>>>classX(Generic[P]):......>>>X[int,str]__main__.X[(<class 'int'>, <class 'str'>)]>>>X[[int,str]]__main__.X[(<class 'int'>, <class 'str'>)]

Do note that generics withParamSpec may not have correct__parameters__ after substitution in some cases because theyare intended primarily for static type checking.

バージョン 3.10 で変更:Generic can now be parameterized over parameter expressions.SeeParamSpec andPEP 612 for more details.

A user-defined generic class can have ABCs as base classes without a metaclassconflict. Generic metaclasses are not supported. The outcome of parameterizinggenerics is cached, and most types in the typing module arehashable andcomparable for equality.

Any

Any は特別な種類の型です。静的型検査器はすべての型をAny と互換として扱い、Any をすべての型と互換として扱います。

これは、Any 型の値では、任意の演算やメソッドの呼び出しが行えることを意味します:

fromtypingimportAnya:Any=Nonea=[]# OKa=2# OKs:str=''s=a# OKdeffoo(item:Any)->int:# Passes type checking; 'item' could be any type,# and that type might have a 'bar' methoditem.bar()...

Any 型の値をより詳細な型に代入する時に型検査が行われないことに注意してください。例えば、静的型検査器はas に代入する時、sstr 型として宣言されていて実行時にint の値を受け取るとしても、エラーを報告しません。

さらに、返り値や引数の型のないすべての関数は暗黙的にAny を使用します。

deflegacy_parser(text):...returndata# A static type checker will treat the above# as having the same signature as:deflegacy_parser(text:Any)->Any:...returndata

この挙動により、動的型付けと静的型付けが混在したコードを書かなければならない時にAny非常口 として使用することができます。

Any の挙動とobject の挙動を対比しましょう。Any と同様に、すべての型はobject のサブタイプです。しかしながら、Any と異なり、逆は成り立ちません:object はすべての他の型のサブタイプではありません

これは、ある値の型がobject のとき、型検査器はこれについてのほとんどすべての操作を拒否し、これをより特殊化された変数に代入する (または返り値として利用する) ことは型エラーになることを意味します。例えば:

defhash_a(item:object)->int:# Fails type checking; an object does not have a 'magic' method.item.magic()...defhash_b(item:Any)->int:# Passes type checkingitem.magic()...# Passes type checking, since ints and strs are subclasses of objecthash_a(42)hash_a("foo")# Passes type checking, since Any is compatible with all typeshash_b(42)hash_b("foo")

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

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

初めはPEP 484 は Python の静的型システムを名前的部分型 を使って定義していました。名前的部分型とは、クラスB が期待されているところにクラスA が許容されるのはAB のサブクラスの場合かつその場合に限る、ということです。

前出の必要条件は、Iterable などの抽象基底クラスにも当て嵌まります。この型付け手法の問題は、この手法をサポートするためにクラスに明確な型付けを行う必要があることで、これは pythonic ではなく、普段行っている 慣用的な Python コードへの動的型付けとは似ていません。例えば、次のコードはPEP 484 に従ったものです

fromcollections.abcimportSized,Iterable,IteratorclassBucket(Sized,Iterable[int]):...def__len__(self)->int:...def__iter__(self)->Iterator[int]:...

PEP 544 によって上にあるようなクラス定義で基底クラスを明示しないコードをユーザーが書け、静的型チェッカーでBucketSizedIterable[int] 両方のサブタイプだと暗黙的に見なせるようになり、この問題が解決しました。これはstructural subtyping (構造的部分型) (あるいは、静的ダックタイピング) として知られています:

fromcollections.abcimportIterator,IterableclassBucket:# Note: no base classes...def__len__(self)->int:...def__iter__(self)->Iterator[int]:...defcollect(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

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

fromtypingimportNoReturndefstop()->NoReturn:raiseRuntimeError('no way')

バージョン 3.5.4 で追加.

バージョン 3.6.2 で追加.

typing.TypeAlias

Special annotation for explicitly declaring atype alias.For example:

fromtypingimportTypeAliasFactors:TypeAlias=list[int]

SeePEP 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 shorthandint|str. Using that shorthand is recommended. Details:

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

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

    Union[Union[int,str],float]==Union[int,str,float]
  • 引数が一つのユニオン型は消えます。例えば:

    Union[int]==int# The constructor actually returns int
  • 冗長な実引数は飛ばされます。例えば:

    Union[int,str,int]==Union[int,str]==int|str
  • ユニオン型を比較するとき引数の順序は無視されます。例えば:

    Union[int,str]==Union[str,int]
  • Union のサブクラスを作成したり、インスタンスを作成することは出来ません。

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

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

バージョン 3.10 で変更:ユニオン型はX|Y のように書けるようになりました。union型の表現 を参照ください。

typing.Optional

オプショナル型。

Optional[X]X|None (やUnion[X,None]) と同等です。

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

deffoo(arg:int=0)->None:...

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

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

バージョン 3.10 で変更:OptionalはX|None のように書けるようになりました。 ref:union型の表現 <types-union> を参照ください。

typing.Callable

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

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

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

callable が別の callable を引数に取る場合は、ParamSpec を使えば両者のパラメータ引数の依存関係を表現することができます。さらに、ある callable が別の callable から引数を追加したり削除したりする場合は、Concatenate 演算子を使うことで表現できます。その場合、callable の型はCallable[ParamSpecVariable,ReturnType]Callable[Concatenate[Arg1Type,Arg2Type,...,ParamSpecVariable],ReturnType] という形になります。

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

バージョン 3.10 で変更:CallableParamSpecConcatenate をサポートしました。詳細はPEP 612 を参照してください。

参考

The documentation forParamSpec andConcatenate provideexamples of usage withCallable.

typing.Concatenate

Used withCallable andParamSpec to type annotate a higherorder callable which adds, removes, or transforms parameters of anothercallable. Usage is in the formConcatenate[Arg1Type,Arg2Type,...,ParamSpecVariable].Concatenateis currently only valid when used as the first argument to aCallable.The last parameter toConcatenate must be aParamSpec.

For example, to annotate a decoratorwith_lock which provides athreading.Lock to the decorated function,Concatenate can beused to indicate thatwith_lock expects a callable which takes in aLock as the first argument, and returns a callable with a different typesignature. In this case, theParamSpec indicates that the returnedcallable's parameter types are dependent on the parameter types of thecallable being passed in:

fromcollections.abcimportCallablefromthreadingimportLockfromtypingimportConcatenate,ParamSpec,TypeVarP=ParamSpec('P')R=TypeVar('R')# Use this lock to ensure that only one thread is executing a function# at any time.my_lock=Lock()defwith_lock(f:Callable[Concatenate[Lock,P],R])->Callable[P,R]:'''A type-safe decorator which provides a lock.'''definner(*args:P.args,**kwargs:P.kwargs)->R:# Provide the lock as the first argument.returnf(my_lock,*args,**kwargs)returninner@with_lockdefsum_threadsafe(lock:Lock,numbers:list[float])->float:'''Add a list of numbers together in a thread-safe manner.'''withlock:returnsum(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 で追加.

参考

classtyping.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] は共変であることに注意してください:

classUser:...classBasicUser(User):...classProUser(User):...classTeamUser(User):...# Accepts User, BasicUser, ProUser, TeamUser, ...defmake_new_user(user_class:Type[User])->User:# ...returnuser_class()

Type[C] が共変だということは、C の全てのサブクラスは、C と同じシグネチャのコンストラクタとクラスメソッドを実装すべきだということになります。型チェッカーはこの規則への違反に印を付けるべきですが、サブクラスでのコンストラクタ呼び出しで、指定された基底クラスのコンストラクタ呼び出しに適合するものは許可すべきです。この特別な場合を型チェッカーがどう扱うべきかについては、PEP 484 の将来のバージョンで変更されるかもしれません。

Type で許されているパラメータは、クラス、Any型変数 あるいは、それらの直和型だけです。例えば次のようになります:

defnew_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 つ) が同等な値を持つことを表すのに使える型です。

defvalidate_simple(data:Any)->Literal[True]:# always returns True...MODE=Literal['r','rb','w','wb']defopen_helper(file:str,mode:MODE)->str:...open_helper('/some/path','r')# Passes type checkopen_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 でラップされた変数アノテーションによって、ある属性はクラス変数として使うつもりであり、そのクラスのインスタンスから設定すべきではないということを示せます。使い方は次のようになります:

classStarship:stats:ClassVar[dict[str,int]]={}# class variabledamage:int=10# instance variable

ClassVar は型のみを受け入れ、それ以外は受け付けられません。

ClassVar はクラスそのものではなく、isinstance()issubclass() で使うべきではありません。ClassVar は Python の実行時の挙動を変えませんが、サードパーティの型検査器で使えます。例えば、型チェッカーは次のコードをエラーとするかもしれません:

enterprise_d=Starship(3000)enterprise_d.stats={}# Error, setting class variable on instanceStarship.stats={}# This is OK

バージョン 3.5.3 で追加.

typing.Final

特別な型付けの構成要素で、名前の割り当て直しやサブクラスでのオーバーライドができないことを型チェッカーに示すためのものです。例えば:

MAX_SIZE:Final=9000MAX_SIZE+=1# Error reported by type checkerclassConnection:TIMEOUT:Final[int]=10classFastConnector(Connection):TIMEOUT=1# Error reported by type checker

この機能は実行時には検査されません。詳細についてはPEP 591 を参照してください。

バージョン 3.8 で追加.

typing.Annotated

PEP 593 (Flexiblefunctionandvariableannotations) で導入された型で、コンテキストに特定のメタデータ (もしかすると、可変個引数の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 (ifat all) is the responsibility of the tool or library encountering theAnnotated type. A tool or library encountering anAnnotated typecan scan through the annotations to determine if they are of interest(e.g., usingisinstance()).

When a tool or a library does not support annotations or encounters anunknown annotation it should just ignore it and treat annotated type asthe underlying type.

It's up to the tool consuming the annotations to decide whether theclient is allowed to have several annotations on one type and how tomerge those annotations.

Since theAnnotated type allows you to put several annotations ofthe same (or different) type(s) on any node, the tools or librariesconsuming those annotations are in charge of dealing with potentialduplicates. For example, if you are doing value range analysis you mightallow this:

T1=Annotated[int,ValueRange(-10,5)]T2=Annotated[T1,ValueRange(-20,3)]

Passinginclude_extras=True toget_type_hints() lets oneaccess the extra annotations at runtime.

The details of the syntax:

  • The first argument toAnnotated must be a valid type

  • Multiple type annotations are supported (Annotated supports variadicarguments):

    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 equalitychecks:

    Annotated[int,ValueRange(3,10),ctype("char")]!=Annotated[int,ctype("char"),ValueRange(3,10)]
  • NestedAnnotated types are flattened, with metadata orderedstarting 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-definedtype guard function.TypeGuard only accepts a single type argument.At runtime, functions marked this way should return a boolean.

TypeGuard aims to benefittype narrowing -- a technique used by statictype checkers to determine a more precise type of an expression within aprogram's code flow. Usually type narrowing is done by analyzingconditional code flow and applying the narrowing to a block of code. Theconditional expression here is sometimes referred to as a "type guard":

defis_str(val:str|float):# "isinstance" type guardifisinstance(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 functionas a type guard. Such a function should useTypeGuard[...] as itsreturn type to alert static type checkers to this intention.

Using->TypeGuard tells the static type checker that for a givenfunction:

  1. The return value is a boolean.

  2. If the return value isTrue, the type of its argumentis the type insideTypeGuard.

例えば:

defis_str_list(val:List[object])->TypeGuard[List[str]]:'''Determines whether all objects in the list are strings'''returnall(isinstance(x,str)forxinval)deffunc1(val:List[object]):ifis_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!")

Ifis_str_list is a class or instance method, then the type inTypeGuard maps to the type of the second parameter aftercls orself.

In short, the formdeffoo(arg:TypeA)->TypeGuard[TypeB]:...,means that iffoo(arg) returnsTrue, thenarg narrows fromTypeA toTypeB.

注釈

TypeB need not be a narrower form ofTypeA -- it can even be awider form. The main reason is to allow for things likenarrowingList[object] toList[str] even though the latteris not a subtype of the former, sinceList is invariant.The responsibility of writing type-safe type guards is left to the user.

TypeGuard also works with type variables. SeePEP 647 for more details.

バージョン 3.10 で追加.

Building generic types

These are not used in annotations. They are building blocks for creating generic types.

classtyping.Generic

ジェネリック型のための抽象基底クラスです。

ジェネリック型は典型的にはこのクラスを1つ以上の型変数によってインスタンス化したものを継承することによって宣言されます。例えば、ジェネリックマップ型は次のように定義することが出来ます:

classMapping(Generic[KT,VT]):def__getitem__(self,key:KT)->VT:...# Etc.

このクラスは次のように使用することが出来ます:

X=TypeVar('X')Y=TypeVar('Y')deflookup_name(mapping:Mapping[X,Y],key:X,default:Y)->Y:try:returnmapping[key]exceptKeyError:returndefault
classtyping.TypeVar

型変数です。

使い方:

T=TypeVar('T')# Can be anythingS=TypeVar('S',bound=str)# Can be any subtype of strA=TypeVar('A',str,bytes)# Must be exactly str or bytes

型変数は主として静的型検査器のために存在します。型変数はジェネリック型やジェネリック関数の定義の引数として役に立ちます。ジェネリック型についての詳細はGeneric を参照してください。ジェネリック関数は以下のように動作します:

defrepeat(x:T,n:int)->Sequence[T]:"""Return a list containing n references to x."""return[x]*ndefprint_capitalized(x:S)->S:"""Print x capitalized, and return x."""print(x.capitalize())returnxdefconcatenate(x:A,y:A)->A:"""Add two strings or bytes objects together."""returnx+y

Note that type variables can bebound,constrained, or neither, butcannot be both boundand constrained.

Constrained type variables and bound type variables have differentsemantics in several important ways. Using aconstrained type variablemeans that theTypeVar can only ever be solved as being exactly one ofthe 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 inc=concatenate('one',b'two')# error: type variable 'A' can be either 'str' or 'bytes' in a function call, but not both

Using abound type variable, however, means that theTypeVar will besolved using the most specific type possible:

print_capitalized('a string')# Ok, output has type 'str'classStringSubclass(str):passprint_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 orprotocols), and even unions of types:

U=TypeVar('U',bound=str|bytes)# Can be any subtype of the union str|bytesV=TypeVar('V',bound=SupportsAbs)# Can be anything with an __abs__ method

Bound type variables are particularly useful for annotatingclassmethods that serve as alternative constructors.In the following example (byRaymond Hettinger), thetype variableC is bound to theCircle class through the use of aforward reference. Using this type variable to annotate thewith_circumference classmethod, rather than hardcoding the return typeasCircle, means that a type checker can correctly infer the returntype even if the method is called on a subclass:

importmathC=TypeVar('C',bound='Circle')classCircle:"""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@classmethoddefwith_circumference(cls:type[C],circumference:float)->C:"""Create a circle with the specified circumference"""radius=circumference/(math.pi*2)returncls(radius)classTire(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 passingcovariant=True orcontravariant=True. SeePEP 484 for moredetails. By default, type variables are invariant.

classtyping.ParamSpec(name,*,bound=None,covariant=False,contravariant=False)

Parameter specification variable. A specialized version oftypevariables.

使い方:

P=ParamSpec('P')

Parameter specification variables exist primarily for the benefit of statictype checkers. They are used to forward the parameter types of onecallable to another callable -- a pattern commonly found in higher orderfunctions and decorators. They are only valid when used inConcatenate,or as the first argument toCallable, or as parameters for user-definedGenerics. SeeGeneric for more information on generic types.

For example, to add basic logging to a function, one can create a decoratoradd_logging to log function calls. The parameter specification variabletells the type checker that the callable passed into the decorator and thenew callable returned by it have inter-dependent type parameters:

fromcollections.abcimportCallablefromtypingimportTypeVar,ParamSpecimportloggingT=TypeVar('T')P=ParamSpec('P')defadd_logging(f:Callable[P,T])->Callable[P,T]:'''A type-safe decorator to add logging to a function.'''definner(*args:P.args,**kwargs:P.kwargs)->T:logging.info(f'{f.__name__} was called')returnf(*args,**kwargs)returninner@add_loggingdefadd_two(x:float,y:float)->float:'''Add two numbers together.'''returnx+y

WithoutParamSpec, the simplest way to annotate this previously was touse aTypeVar with boundCallable[...,Any]. However thiscauses two problems:

  1. The type checker can't type check theinner function because*args and**kwargs have to be typedAny.

  2. cast() may be required in the body of theadd_loggingdecorator when returning theinner function, or the static typechecker must be told to ignore thereturninner.

args
kwargs

SinceParamSpec captures both positional and keyword parameters,P.args andP.kwargs can be used to split aParamSpec into itscomponents.P.args represents the tuple of positional parameters in agiven call and should only be used to annotate*args.P.kwargsrepresents the mapping of keyword parameters to their values in a given call,and should be only be used to annotate**kwargs. Bothattributes require the annotated parameter to be in scope. At runtime,P.args andP.kwargs are instances respectively ofParamSpecArgs andParamSpecKwargs.

Parameter specification variables created withcovariant=True orcontravariant=True can be used to declare covariant or contravariantgeneric types. Thebound argument is also accepted, similar toTypeVar. However the actual semantics of these keywords are yet tobe decided.

バージョン 3.10 で追加.

注釈

Only parameter specification variables defined in global scope canbe pickled.

参考

typing.ParamSpecArgs
typing.ParamSpecKwargs

Arguments and keyword arguments attributes of aParamSpec. TheP.args attribute of aParamSpec is an instance ofParamSpecArgs,andP.kwargs is an instance ofParamSpecKwargs. They are intendedfor runtime introspection and have no special meaning to static type checkers.

Callingget_origin() on either of these objects will return theoriginalParamSpec:

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

バージョン 3.10 で追加.

typing.AnyStr

AnyStr is aconstrainedtypevariable defined asAnyStr=TypeVar('AnyStr',str,bytes).

他の種類の文字列を混ぜることなく、任意の種類の文字列を許す関数によって使われることを意図しています。

defconcat(a:AnyStr,b:AnyStr)->AnyStr:returna+bconcat(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
classtyping.Protocol(Generic)

プロトコルクラスの基底クラス。プロトコルクラスは次のように定義されます:

classProto(Protocol):defmeth(self)->int:...

このようなクラスは主に構造的部分型 (静的ダックタイピング) を認識する静的型チェッカーが使います。例えば:

classC:defmeth(self)->int:return0deffunc(x:Proto)->int:returnx.meth()func(C())# Passes static type check

詳細についてはPEP 544 を参照してください。runtime_checkable() (後で説明します) でデコレートされたプロトコルクラスは、与えられたメソッドがあることだけを確認し、その型シグネチャは全く見ない安直な動作をする実行時プロトコルとして振る舞います。

プロトコルクラスはジェネリックにもできます。例えば:

classGenProto(Protocol[T]):defmeth(self)->T:...

バージョン 3.8 で追加.

@typing.runtime_checkable

Mark a protocol class as a runtime protocol.

Such a protocol can be used withisinstance() andissubclass().This raisesTypeError when applied to a non-protocol class. Thisallows a simple-minded structural check, very similar to "one trick ponies"incollections.abc such asIterable. For example:

@runtime_checkableclassClosable(Protocol):defclose(self):...assertisinstance(open('/some/file'),Closable)@runtime_checkableclassNamed(Protocol):name:strimportthreadingassertisinstance(threading.Thread(name='Bob'),Named)

注釈

runtime_checkable() will check only the presence of the requiredmethods or attributes, not their type signatures or types.For example,ssl.SSLObjectis a class, therefore it passes anissubclass()check againstCallable. However, thessl.SSLObject.__init__ method exists only to raise aTypeError with a more informative message, therefore makingit impossible to call (instantiate)ssl.SSLObject.

注釈

Anisinstance() check against a runtime-checkable protocol can besurprisingly slow compared to anisinstance() check againsta non-protocol class. Consider using alternative idioms such ashasattr() calls for structural checks in performance-sensitivecode.

バージョン 3.8 で追加.

Other special directives

These are not used in annotations. They are building blocks for declaring types.

classtyping.NamedTuple

collections.namedtuple() の型付き版です。

使い方:

classEmployee(NamedTuple):name:strid:int

これは次と等価です:

Employee=collections.namedtuple('Employee',['name','id'])

フィールドにデフォルト値を与えるにはクラス本体で代入してください:

classEmployee(NamedTuple):name:strid:int=3employee=Employee('Guido')assertemployee.id==3

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

最終的に出来上がるクラスには、フィールド名をフィールド型へ対応付ける辞書を提供する__annotations__ 属性が追加されています。(フィールド名は_fields 属性に、デフォルト値は_field_defaults 属性に格納されていて、両方ともnamedtuple() API の一部分です。)

NamedTuple のサブクラスは docstring やメソッドも持てます:

classEmployee(NamedTuple):"""Represents an employee."""name:strid:int=3def__repr__(self)->str:returnf'<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__ 属性を使ってください。

classtyping.NewType(name,tp)

A helper class to indicate a distinct type to a typechecker,seeNewType. At runtime it returns an object that returnsits 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.

classtyping.TypedDict(dict)

Special construct to add type hints to a dictionary.At runtime it is a plaindict.

TypedDict は、その全てのインスタンスにおいてキーの集合が固定されていて、各キーに対応する値が全てのインスタンスで同じ型を持つことが期待される辞書型を宣言します。この期待は実行時にはチェックされず、型チェッカーでのみ強制されます。使用方法は次の通りです:

classPoint2D(TypedDict):x:inty:intlabel:stra:Point2D={'x':1,'y':2,'label':'good'}# OKb:Point2D={'z':3,'label':'bad'}# Fails type checkassertPoint2D(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 notsupportPEP 526,TypedDict supports two additional equivalentsyntactic 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 valididentifiers, for example because they are keywords or contain hyphens.Example:

# raises SyntaxErrorclassPoint2D(TypedDict):in:int# 'in' is a keywordx-y:int# name with hyphens# OK, functional syntaxPoint2D=TypedDict('Point2D',{'in':int,'x-y':int})

By default, all keys must be present in aTypedDict. It is possible tooverride this by specifying totality.Usage:

classPoint2D(TypedDict,total=False):x:inty:int

This means that aPoint2DTypedDict can have any of the keysomitted. A type checker is only expected to support a literalFalse orTrue as the value of thetotal argument.True is the default,and makes all items defined in the class body required.

It is possible for aTypedDict type to inherit from one or more otherTypedDict typesusing the class-based syntax.Usage:

classPoint3D(Point2D):z:int

Point3D has three items:x,y andz. It is equivalent to thisdefinition:

classPoint3D(TypedDict):x:inty:intz:int

ATypedDict cannot inherit from a non-TypedDict class,notably includingGeneric. For example:

classX(TypedDict):x:intclassY(TypedDict):y:intclassZ(object):pass# A non-TypedDict classclassXY(X,Y):pass# OKclassXZ(X,Z):pass# raises TypeErrorT=TypeVar('T')classXT(X,Generic[T]):pass# raises TypeError

ATypedDict can be introspected via annotations dicts(seeAnnotations Best Practices for more information on annotations best practices),__total__,__required_keys__, and__optional_keys__.

__total__

Point2D.__total__ gives the value of thetotal argument.Example:

>>>fromtypingimportTypedDict>>>classPoint2D(TypedDict):pass>>>Point2D.__total__True>>>classPoint2D(TypedDict,total=False):pass>>>Point2D.__total__False>>>classPoint3D(Point2D):pass>>>Point3D.__total__True
__required_keys__

バージョン 3.9 で追加.

__optional_keys__

Point2D.__required_keys__ andPoint2D.__optional_keys__ returnfrozenset objects containing required and non-required keys, respectively.Currently the only way to declare both required and non-required keys in thesameTypedDict is mixed inheritance, declaring aTypedDict with one valuefor thetotal argument and then inheriting it from anotherTypedDict witha different value fortotal.Usage:

>>>classPoint2D(TypedDict,total=False):...x:int...y:int...>>>classPoint3D(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

classtyping.Dict(dict, MutableMapping[KT, VT])

dict のジェネリック版です。返り値の型のアノテーションをつけることに便利です。引数にアノテーションをつけるためには、Mapping のような抽象コレクション型を使うことが好ましいです。

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

defcount_words(text:str)->Dict[str,int]:...

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

classtyping.List(list, MutableSequence[T])

list のジェネリック版です。返り値の型のアノテーションをつけるのに便利です。引数にアノテーションをつけるためには、SequenceIterable のような抽象コレクション型を使うことが好ましいです。

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

T=TypeVar('T',int,float)defvec2(x:T,y:T)->List[T]:return[x,y]defkeep_positives(vector:Sequence[T])->List[T]:return[itemforiteminvectorifitem>0]

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

classtyping.Set(set, MutableSet[T])

builtins.set のジェネリック版です。返り値の型のアノテーションをつけるのに便利です。引数にアノテーションをつけるためには、AbstractSet のような抽象コレクション型を使うことが好ましいです。

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

classtyping.FrozenSet(frozenset, AbstractSet[T_co])

builtins.frozenset のジェネリック版です。

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

注釈

Tuple is a special form.

Corresponding to types incollections

classtyping.DefaultDict(collections.defaultdict, MutableMapping[KT, VT])

collections.defaultdict のジェネリック版です。

バージョン 3.5.2 で追加.

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

classtyping.OrderedDict(collections.OrderedDict, MutableMapping[KT, VT])

collections.OrderedDict のジェネリック版です。

バージョン 3.7.2 で追加.

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

classtyping.ChainMap(collections.ChainMap, MutableMapping[KT, VT])

collections.ChainMap のジェネリック版です。

バージョン 3.5.4 で追加.

バージョン 3.6.1 で追加.

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

classtyping.Counter(collections.Counter, Dict[T, int])

collections.Counter のジェネリック版です。

バージョン 3.5.4 で追加.

バージョン 3.6.1 で追加.

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

classtyping.Deque(deque, MutableSequence[T])

collections.deque のジェネリック版です。

バージョン 3.5.4 で追加.

バージョン 3.6.1 で追加.

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

Other concrete types

classtyping.IO
classtyping.TextIO
classtyping.BinaryIO

ジェネリック型IO[AnyStr] とそのサブクラスのTextIO(IO[str]) およびBinaryIO(IO[bytes]) は、open() 関数が返すような I/O ストリームの型を表します。

Deprecated since version 3.8, will be removed in version 3.13:Thetyping.io namespace is deprecated and will be removed.These types should be directly imported fromtyping instead.

classtyping.Pattern
classtyping.Match

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

Deprecated since version 3.8, will be removed in version 3.13:Thetyping.re namespace is deprecated and will be removed.These types should be directly imported fromtyping instead.

バージョン 3.9 で非推奨:ClassesPattern andMatch fromre now support[].SeePEP 585 andジェネリックエイリアス型.

classtyping.Text

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

Text は Python 2 と Python 3 の両方と互換性のある方法で値が unicode 文字列を含んでいなければならない場合に使用してください。

defadd_unicode_checkmark(text:Text)->Text:returntext+u'\u2713'

バージョン 3.5.2 で追加.

抽象基底クラス

Corresponding to collections incollections.abc

classtyping.AbstractSet(Collection[T_co])

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

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

classtyping.ByteString(Sequence[int])

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

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

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

バージョン 3.9 で非推奨:collections.abc.ByteString now supports subscripting ([]).SeePEP 585 andジェネリックエイリアス型.

classtyping.Collection(Sized, Iterable[T_co], Container[T_co])

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

バージョン 3.6.0 で追加.

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

classtyping.Container(Generic[T_co])

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

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

classtyping.ItemsView(MappingView, AbstractSet[tuple[KT_co, VT_co]])

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

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

classtyping.KeysView(MappingView, AbstractSet[KT_co])

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

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

classtyping.Mapping(Collection[KT], Generic[KT, VT_co])

collections.abc.Mapping のジェネリック版です。この型は次のように使えます:

defget_position_in_index(word_list:Mapping[str,int],word:str)->int:returnword_list[word]

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

classtyping.MappingView(Sized)

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

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

classtyping.MutableMapping(Mapping[KT, VT])

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

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

classtyping.MutableSequence(Sequence[T])

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

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

classtyping.MutableSet(AbstractSet[T])

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

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

classtyping.Sequence(Reversible[T_co], Collection[T_co])

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

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

classtyping.ValuesView(MappingView, Collection[_VT_co])

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

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

Corresponding to other types incollections.abc

classtyping.Iterable(Generic[T_co])

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

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

classtyping.Iterator(Iterable[T_co])

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

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

classtyping.Generator(Iterator[T_co], Generic[T_co, T_contra, V_co])

ジェネレータはジェネリック型Generator[YieldType,SendType,ReturnType] によってアノテーションを付けられます。例えば:

defecho_round()->Generator[int,float,str]:sent=yield0whilesent>=0:sent=yieldround(sent)return'Done'

typing モジュールの多くの他のジェネリクスと違いGeneratorSendType は共変や不変ではなく、反変として扱われることに注意してください。

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

definfinite_stream(start:int)->Generator[int,None,None]:whileTrue:yieldstartstart+=1

代わりに、ジェネレータをIterable[YieldType]Iterator[YieldType] という返り値の型でアノテーションをつけることもできます:

definfinite_stream(start:int)->Iterator[int]:whileTrue:yieldstartstart+=1

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

classtyping.Hashable

collections.abc.Hashable へのエイリアスです。

classtyping.Reversible(Iterable[T_co])

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

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

classtyping.Sized

collections.abc.Sized へのエイリアスです。

Asynchronous programming

classtyping.Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co])

collections.abc.Coroutine のジェネリック版です。変性と型変数の順序はGenerator のものと対応しています。例えば次のようになります:

fromcollections.abcimportCoroutinec:Coroutine[list[str],str,int]# Some coroutine defined elsewherex=c.send('hi')# Inferred type of 'x' is list[str]asyncdefbar()->None:y=awaitc# Inferred type of 'y' is int

バージョン 3.5.3 で追加.

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

classtyping.AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra])

非同期ジェネレータはジェネリック型AsyncGenerator[YieldType,SendType] によってアノテーションを付けられます。例えば:

asyncdefecho_round()->AsyncGenerator[int,float]:sent=yield0whilesent>=0.0:rounded=awaitround(sent)sent=yieldrounded

通常のジェネレータと違って非同期ジェネレータは値を返せないので、ReturnType 型引数はありません。Generator と同様に、SendType は反変的に振る舞います。

ジェネレータが値を yield するだけなら、SendTypeNone にします:

asyncdefinfinite_stream(start:int)->AsyncGenerator[int,None]:whileTrue:yieldstartstart=awaitincrement(start)

あるいは、ジェネレータがAsyncIterable[YieldType]AsyncIterator[YieldType] のいずれかの戻り値型を持つとアノテートします:

asyncdefinfinite_stream(start:int)->AsyncIterator[int]:whileTrue:yieldstartstart=awaitincrement(start)

バージョン 3.6.1 で追加.

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

classtyping.AsyncIterable(Generic[T_co])

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

バージョン 3.5.2 で追加.

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

classtyping.AsyncIterator(AsyncIterable[T_co])

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

バージョン 3.5.2 で追加.

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

classtyping.Awaitable(Generic[T_co])

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

バージョン 3.5.2 で追加.

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

コンテキストマネージャ型

classtyping.ContextManager(Generic[T_co])

contextlib.AbstractContextManager のジェネリック版です。

バージョン 3.5.4 で追加.

バージョン 3.6.0 で追加.

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

classtyping.AsyncContextManager(Generic[T_co])

contextlib.AbstractAsyncContextManager のジェネリック版です。

バージョン 3.5.4 で追加.

バージョン 3.6.2 で追加.

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

プロトコル

These protocols are decorated withruntime_checkable().

classtyping.SupportsAbs

返り値の型と共変な抽象メソッド__abs__ を備えた ABC です。

classtyping.SupportsBytes

抽象メソッド__bytes__ を備えた ABC です。

classtyping.SupportsComplex

抽象メソッド__complex__ を備えた ABC です。

classtyping.SupportsFloat

抽象メソッド__float__ を備えた ABC です。

classtyping.SupportsIndex

抽象メソッド__index__ を備えた ABC です。

バージョン 3.8 で追加.

classtyping.SupportsInt

抽象メソッド__int__ を備えた ABC です。

classtyping.SupportsRound

返り値の型と共変な抽象メソッド__round__ を備えた ABC です。

Functions and decorators

typing.cast(typ,val)

値をある型にキャストします。

この関数は値を変更せずに返します。型検査器に対して、返り値が指定された型を持っていることを通知しますが、実行時には意図的に何も検査しません。(その理由は、処理をできる限り速くしたかったためです。)

@typing.overload

@overload デコレータを使うと、引数の型の複数の組み合わせをサポートする関数やメソッドを書けるようになります。@overload 付きの定義を並べた後ろに、(同じ関数やメソッドの)@overload 無しの定義が来なければなりません。@overload 付きの定義は型チェッカーのためでしかありません。というのも、@overload 付きの定義は@overload 無しの定義で上書きされるからです。後者は実行時に使われますが、型チェッカーからは無視されるべきなのです。実行時には、@overload 付きの関数を直接呼び出すとNotImplementedError を送出します。次のコードはオーバーロードを使うことで直和型や型変数を使うよりもより正確な型が表現できる例です:

@overloaddefprocess(response:None)->None:...@overloaddefprocess(response:int)->tuple[int,str]:...@overloaddefprocess(response:bytes)->str:...defprocess(response):<actualimplementation>

詳細と他の型付け意味論との比較はPEP 484 を参照してください。

@typing.final

A decorator to indicate to type checkers that the decorated methodcannot be overridden, and the decorated class cannot be subclassed.For example:

classBase:@finaldefdone(self)->None:...classSub(Base):defdone(self)->None:# Error reported by type checker...@finalclassLeaf:...classOther(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_onlyclassResponse:# private or not available at runtimecode:intdefget_header(self,name:str)->str:...deffetch_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 allAnnotated[T,...] withT,unlessinclude_extras is set toTrue (seeAnnotated formore information). For example:

classStudent(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 importedtype aliases that include forward references.Enabling postponed evaluation of annotations (PEP 563) may removethe need for most forward references.

バージョン 3.9 で変更:Addedinclude_extras parameter as part ofPEP 593.

typing.get_args(tp)
typing.get_origin(tp)

ジェネリック型や特殊な型付け形式についての基本的な内観を提供します。

For a typing object of the formX[Y,Z,...] these functions returnX and(Y,Z,...). IfX is a generic alias for a builtin orcollections class, it gets normalized to the original class.IfX is a union orLiteral contained in anothergeneric type, the order of(Y,Z,...) may be different from the orderof the original arguments[Y,Z,...] due to type caching.For unsupported objects returnNone and() correspondingly.Examples:

assertget_origin(Dict[str,int])isdictassertget_args(Dict[int,str])==(int,str)assertget_origin(Union[int,str])isUnionassertget_args(Union[int,str])==(int,str)

バージョン 3.8 で追加.

typing.is_typeddict(tp)

Check if a type is aTypedDict.

例えば:

classFilm(TypedDict):title:stryear:intis_typeddict(Film)# => Trueis_typeddict(list|str)# => False

バージョン 3.10 で追加.

classtyping.ForwardRef

文字列による前方参照の内部的な型付け表現に使われるクラスです。例えば、List["SomeClass"] は暗黙的にList[ForwardRef("SomeClass")] に変換されます。このクラスはユーザーがインスタンス化するべきではなく、イントロスペクションツールに使われるものです。

注釈

PEP 585 generic types such aslist["SomeClass"] will not beimplicitly transformed intolist[ForwardRef("SomeClass")] and thuswill not automatically resolve tolist[SomeClass].

バージョン 3.7.4 で追加.

定数

typing.TYPE_CHECKING

サードパーティーの静的型検査器がTrue と仮定する特別な定数です。 実行時にはFalse になります。使用例:

ifTYPE_CHECKING:importexpensive_moddeffun(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 theexpensive_mod reference from theinterpreter runtime. Type annotations for local variables are notevaluated, so the second annotation does not need to be enclosed in quotes.

注釈

from__future__importannotations が使われた場合、アノーテーションは関数定義時に評価されません。代わりにアノーテーションは__annotations__ 属性に文字列として保存されます。これによりアノーテーションをシングルクォートで囲む必要がなくなります (PEP 563 を参照してください)。

バージョン 3.5.2 で追加.