26.1. typing — 型ヒントのサポート¶
バージョン 3.5 で追加.
ソースコード: Lib/typing.py
このモジュールは PEP 484 によって規定された型ヒントをサポートします。最も基本的なサポートとして Any、 Union、 Tuple、 Callable、 TypeVar および Generic 型を含みます。完全な仕様は PEP 484 を参照してください。型ヒントの簡単な導入は PEP 483 を参照してください。
以下の関数は文字列を取り文字列を返す関数で、次のようにアノテーションがつけられます:
def greeting(name: str) -> str:
return 'Hello ' + name
関数 greeting で、実引数 name の型は str であり、返り値の型は str であることが期待されます。サブタイプも実引数として受け入れられます。
26.1.1. 型エイリアス¶
型エイリアスは型をエイリアスに代入することで定義されます。この例では Vector と List[float] は交換可能な同義語として扱われます。
from typing import List
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 typing import Dict, Tuple, List
ConnectionOptions = Dict[str, str]
Address = Tuple[str, int]
Server = Tuple[Address, ConnectionOptions]
def broadcast_message(message: str, servers: List[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: List[Tuple[Tuple[str, int], Dict[str, str]]]) -> None:
...
型ヒントとしての None は特別なケースであり、 type(None) によって置き換えられます。
26.1.2. NewType¶
異なる型を作るためには NewType() ヘルパー関数を使います:
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)
これらのチェックは静的型検査器のみによって強制されるということに注意してください。実行時に Derived = NewType('Derived', Base) という文は渡された仮引数をただちに返す Derived 関数を作ります。つまり Derived(some_value) という式は新しいクラスを作ることはなく、通常の関数呼び出し以上のオーバーヘッドがないということを意味します。
より正確に言うと、式 some_value is Derived(some_value) は実行時に常に真を返します。
これはまた Derived は実行時には関数で、実際の型ではないため、これのサブタイプを作ることが出来ないことを意味します。同様に、 Derived 型を基にした NewType() を作ることはできません:
from typing import NewType
UserId = NewType('UserId', int)
# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
# Also does not typecheck
ProUserId = NewType('ProUserId', UserId)
詳細は PEP 484 を参照。
注釈
型エイリアスの使用は2つの型が互いに 同値 であると言うことを宣言していると言うことを思い出してください。 Alias = Original とすると、静的型検査器は Alias をすべての場合で Original と 完全に同値 なものとして扱います。これは複雑な型シグネチャを単純化したい時に有用です。
これに対し、 NewType はある型をもう一方の型の サブタイプ として宣言します。 Derived = NewType('Derived', Original) とすると静的型検査器は Derived を Original の サブクラス として扱います。これは Original 型の値は Derived 型の値が期待される場所で使うことが出来ないと言うことを意味します。これは論理的な誤りを最小の実行時のコストで防ぎたい時に有用です。
26.1.3. 呼び出し可能オブジェクト¶
特定のシグネチャのコールバック関数であることが期待されるフレームワークでは Callable[[Arg1Type, Arg2Type], ReturnType] のように使って型ヒントを与えられます。
例えば:
from typing 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
型ヒントの実引数の型を ellipsis で置き換えることで呼び出しシグニチャを指定せずに callable の戻り値の型を宣言することができます: Callable[..., ReturnType]。
26.1.4. ジェネリクス¶
コンテナ内のオブジェクトについての型情報を一般的な方法では静的に推論出来ないため、抽象基底クラスがコンテナの要素について期待される型を示すために添字表記をサポートするように拡張されました。
from typing import Mapping, Sequence
def notify_by_email(employees: Sequence[Employee],
overrides: Mapping[str, str]) -> None: ...
ジェネリクスは TypeVar と呼ばれる typing で利用できる新しいファクトリを使ってパラメータ化することができます。
from typing import Sequence, TypeVar
T = TypeVar('T') # Declare type variable
def first(l: Sequence[T]) -> T: # Generic function
return l[0]
26.1.5. ユーザー定義のジェネリック型¶
ユーザー定義のクラスはジェネリッククラスとして定義できます。
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 クラスは一つの型引数 T をとることを定義します。これはまたこのクラスの中で T を型として有効にします。
基底クラス Generic は LoggedVar[t] が型として有効になるように __getitem__() を定義したメタクラスを利用します。
from typing import Iterable
def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:
for var in vars:
var.set(0)
ジェネリック型は任意の数の型変数をとることが出来ます、また型変数に制約をつけることが出来ます:
from typing import TypeVar, Generic
...
T = TypeVar('T')
S = TypeVar('S', int, str)
class StrangePair(Generic[T, S]):
...
Generic の引数のそれぞれの型変数は別のものでなければなりません。このため次は無効です:
from typing import TypeVar, Generic
...
T = TypeVar('T')
class Pair(Generic[T, T]): # INVALID
...
Generic を用いて多重継承することが出来ます:
from typing import TypeVar, Generic, Sized
T = TypeVar('T')
class LinkedList(Sized, Generic[T]):
...
ジェネリッククラスを継承するとき、いくつかの型変数を固定することが出来ます:
from typing import TypeVar, Mapping
T = TypeVar('T')
class MyDict(Mapping[str, T]):
...
この場合では MyDict は一つの仮引数 T をとります。
型引数を指定せずにジェネリッククラスを使う場合、それぞれの型引数を Any と仮定します。
次の例では、MyIterable はジェネリックではありませんが Iterable[Any] を暗黙的に継承しています:
from typing import Iterable
class MyIterable(Iterable): # Same as Iterable[Any]
ユーザ定義のジェネリック型エイリアスもサポートされています。例:
from typing import TypeVar, Iterable, Tuple, 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)
The metaclass used by Generic is a subclass of abc.ABCMeta.
A generic class can be an ABC by including abstract methods or properties,
and generic classes can also have ABCs as base classes without a metaclass
conflict. Generic metaclasses are not supported. The outcome of parameterizing
generics is cached, and most types in the typing module are hashable and
comparable for equality.
26.1.6. Any 型¶
Any は特別な種類の型です。静的型検査器はすべての型を Any と互換として扱い、 Any をすべての型と互換として扱います。
つまり、 Any 型の値に対し任意の演算やメソッド呼び出しができ、任意の変数に代入できということです。
from typing import Any
a = None # type: Any
a = [] # OK
a = 2 # OK
s = '' # type: 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
この挙動により、動的型付けと静的型付けが混在したコードを書かなければならない時に :dataAny` を 非常口 として使用することができます。
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 はある値が動的に型付けられることを示すために使用します。
26.1.7. クラス、関数、およびデコレータ¶
このモジュールでは以下のクラス、関数とデコレータを定義します:
-
class
typing.TypeVar¶ 型変数です。
使い方:
T = TypeVar('T') # Can be anything A = TypeVar('A', str, bytes) # Must be str or bytes
型変数は主として静的型検査器のために存在します。型変数はジェネリック型やジェネリック関数の定義の引数として役に立ちます。ジェネリック型についての詳細は Generic クラスを参照してください。ジェネリック関数は以下のように動作します:
def repeat(x: T, n: int) -> Sequence[T]: """Return a list containing n references to x.""" return [x]*n def longest(x: A, y: A) -> A: """Return the longest of two strings.""" return x if len(x) >= len(y) else y
後者の例のシグネチャは本質的に
(str, str) -> strと(bytes, bytes) -> bytesのオーバーロードです。もし引数がstrのサブクラスのインスタンスの場合、返り値は普通のstrであることに注意して下さい。実行時に、
isinstance(x, T)はTypeErrorを送出するでしょう。一般的に、isinstance()とissubclass()は型に対して使用するべきではありません。型変数は
covariant=Trueまたはcontravariant=Trueを渡すことによって共変または反変であることを示せます。詳細は PEP 484 を参照して下さい。デフォルトの型変数は不変です。あるいは、型変数はbound=<type>を使うことで上界を指定することが出来ます。これは、型変数に (明示的または非明示的に) 代入された実際の型が境界の型のサブクラスでなければならないということを意味します、PEP 484 も参照。
-
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.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()
The fact that
Type[C]is covariant implies that all subclasses ofCshould implement the same constructor signature and class method signatures asC. The type checker should flag violations of this, but should also allow constructor calls in subclasses that match the constructor calls in the indicated base class. How the type checker is required to handle this particular case may change in future revisions of PEP 484.Typeで許されているパラメータは、クラスかクラスの直和型かAnyです。 例えば次のようになります:def new_non_team_user(user_class: Type[Union[BaseUser, ProUser]]): ...
Type[Any]はTypeと等しく、さらにこれはtypeと等しいもので、 Python のメタクラス階層のルートです。
-
class
typing.Iterable(Generic[T_co])¶ collections.abc.Iterableのジェネリック版です。
-
class
typing.Iterator(Iterable[T_co])¶ collections.abc.Iteratorのジェネリック版です。
-
class
typing.Reversible(Iterable[T_co])¶ collections.abc.Reversibleのジェネリック版です。
-
class
typing.SupportsInt¶ 一つの抽象メソッド
__int__を備えた ABC です。
-
class
typing.SupportsFloat¶ 一つの抽象メソッド
__float__を備えた ABC です。
-
class
typing.SupportsAbs¶ 返り値の型が共変である、一つの抽象メソッド
__abs__を備えた ABC です。
-
class
typing.SupportsRound¶ 返り値の型が共変である、一つの抽象メソッド
__round__を備えた ABC です。
-
class
typing.Container(Generic[T_co])¶ collections.abc.Containerのジェネリック版です。
-
class
typing.Hashable¶ collections.abc.Hashableへのエイリアス
-
class
typing.Sized¶ collections.abc.Sizedへのエイリアス
-
class
typing.AbstractSet(Sized, Iterable[T_co], Container[T_co])¶ collections.abc.Setのジェネリック版です。
-
class
typing.MutableSet(AbstractSet[T])¶ collections.abc.MutableSetのジェネリック版です。
-
class
typing.Mapping(Sized, Iterable[KT], Container[KT], Generic[VT_co])¶ collections.abc.Mappingのジェネリック版です。
-
class
typing.MutableMapping(Mapping[KT, VT])¶ collections.abc.MutableMappingのジェネリック版です。
-
class
typing.Sequence(Sized, Iterable[T_co], Container[T_co])¶ collections.abc.Sequenceのジェネリック版です。
-
class
typing.MutableSequence(Sequence[T])¶ collections.abc.MutableSequenceのジェネリック版です。
-
class
typing.ByteString(Sequence[int])¶ collections.abc.ByteStringのジェネリック版です。この型は
bytesとbytearray、memoryviewを表します。この型の省略形として、
bytesを上に挙げた任意の型の引数にアノテーションをつけることに使えます。
-
class
typing.Deque(deque, MutableSequence[T])¶ collections.dequeのジェネリック版です。バージョン 3.5.4 で追加.
-
class
typing.List(list, MutableSequence[T])¶ listのジェネリック版です。返り値の型のアノテーションをつけることに便利です。引数にアノテーションをつけるためには、MappingやSequence、AbstractSetのような抽象コレクション型を使うことが好ましいです。この型は以下のように使うことが出来ます:
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]
-
class
typing.Set(set, MutableSet[T])¶ builtins.setのジェネリック版です。
-
class
typing.FrozenSet(frozenset, AbstractSet[T_co])¶ builtins.frozensetのジェネリック版です。
-
class
typing.MappingView(Sized, Iterable[T_co])¶ collections.abc.MappingViewのジェネリック版です。
-
class
typing.KeysView(MappingView[KT_co], AbstractSet[KT_co])¶ collections.abc.KeysViewのジェネリック版です。
-
class
typing.ItemsView(MappingView, Generic[KT_co, VT_co])¶ collections.abc.ItemsViewのジェネリック版です。
-
class
typing.ValuesView(MappingView[VT_co])¶ collections.abc.ValuesViewのジェネリック版です。
-
class
typing.Awaitable(Generic[T_co])¶ collections.abc.Awaitableのジェネリック版です。
-
class
typing.Coroutine(Awaitable[V_co], Generic[T_co T_contra, V_co])¶ A generic version of
collections.abc.Coroutine. The variance and order of type variables correspond to those ofGenerator, for example:from typing import List, Coroutine c = None # type: Coroutine[List[str], str, int] ... x = c.send('hi') # type: List[str] async def bar() -> None: x = await c # type: int
-
class
typing.AsyncIterable(Generic[T_co])¶ collections.abc.AsyncIterableのジェネリック版です。
-
class
typing.AsyncIterator(AsyncIterable[T_co])¶ collections.abc.AsyncIteratorのジェネリック版です。
-
class
typing.Dict(dict, MutableMapping[KT, VT])¶ dictのジェネリック版です。この型の使い方は以下の通りです:def get_position_in_index(word_list: Dict[str, int], word: str) -> int: return word_list[word]
-
class
typing.DefaultDict(collections.defaultdict, MutableMapping[KT, VT])¶ collections.defaultdictのジェネリック版です。
-
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
-
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.5.4 で追加.
-
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'
-
class
typing.io¶ I/O ストリーム型のためのラッパー名前空間です。
これはジェネリック型
IO[AnyStr]を定義し、TextIOとBinaryIOをそれぞれIO[str]とIO[bytes]のエイリアスとして定義します。これらはopen()によって返されるような I/O ストリームの型を表します。
-
class
typing.re¶ 正規表現のマッチング型のための名前空間です。
これは
re.compile()とre.match()の返り値の型に対応する型エイリアスPatternとMatchを定義します。これらの型 (と対応する関数) はAnyStrについてジェネリックで、Pattern[str]やPattern[bytes]、Match[str]、Match[bytes]のように書くことで具体的にすることが出来ます。
-
typing.NamedTuple(typename, fields)¶ namedtuple の型付き版。
使い方:
Employee = typing.NamedTuple('Employee', [('name', str), ('id', int)])
これは次と等価です:
Employee = collections.namedtuple('Employee', ['name', 'id'])
結果のクラスは一つの余分な属性 _field_types を持っており、フィールド名と型をマップする辞書になっています。(フィールド名は _fields 属性に入っています。これは namedtuple の API の一部です。)
-
typing.NewType(typ)¶ 異なる型であることを型チェッカーに教えるためのヘルパー関数です。 NewType を参照してください。 実行時には、その引数を返す関数を返します。 使い方は次のようになります:
UserId = NewType('UserId', int) first_user = UserId(1)
-
typing.cast(typ, val)¶ 値をある型にキャストします。
これは値を変更せずに返します。型検査器にこれは返り値の型が指定された型を持っていることを知らせますが、故意に実行時に何も検査しません。(これを出来る限り速く行いたかったのです。)
-
typing.get_type_hints(obj[, globals[, locals]])¶ 関数、メソッド、モジュールまたはクラスのオブジェクトの型ヒントを含む辞書を返します。
This is often the same as
obj.__annotations__. In addition, forward references encoded as string literals are handled by evaluating them inglobalsandlocalsnamespaces. If necessary,Optional[t]is added for function and method annotations if a default value equal toNoneis set. For a classC, return a dictionary constructed by merging all the__annotations__alongC.__mro__in reverse order.
-
@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.no_type_check(arg)¶ アノテーションが型ヒントでないことを示すデコレータです。
引数はクラスまたは関数でなければなりません。もし引数がクラスなら、そのクラスに定義されているすべてのメソッドについて再帰的に適用します。(ただし、スーパークラスやサブクラスに定義されているメソッドには適用されません。)
これは関数を適切に変更します。
-
@typing.no_type_check_decorator(decorator)¶ 別のデコレータに
no_type_check()の効果を与えるデコレータです。これは何かの関数をラップするデコレータを
no_type_check()でラップします。
-
typing.Union¶ 直和型;
Union[X, Y]は X または Y を表します。直和型を定義します、例えば
Union[int, str]のように使います。詳細:実引数は型でなければならず、少なくとも一つ必要です。
直和型の直和型は flatten されます、例えば:
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[int, object] == object
直和型のサブクラスを作成したり、インスタンスを作成することは出来ません。
Union[X][Y]と書くことは出来ません。Optional[X]をUnion[X, None]の略記として利用することが出来ます。
-
typing.Optional¶ オプショナル型。
Optional[X]はUnion[X, None]と同値です。これがデフォルト値のある引数であるオプショナル引数と同じ概念ではないと言うことに注意してください。デフォルト値のあるオプショナル引数ではその型アノテーションで
Optionalを使う必要はありません (ただしデフォルトではNoneと推論されます)。必須の引数は明示的な値としてNoneが許されるのであればOptional型も持つことが出来ます。
-
typing.Tuple¶ タプル型;
Tuple[X, Y]は、最初の要素の型が X で、2つ目の要素の型が Y であるような、2つの要素を持つタプルの型です。例:
Tuple[T1, T2]は型変数 T1 と T2 に対応する2つの要素を持つタプルです。Tuple[int, float, str]は int と float、 string のタプルです。同じ型の任意の長さのタプルを指定するには ellipsis リテラルを用います。例:
Tuple[int, ...]。ただのTupleはTuple[Any, ...]と等価で、さらにtupleと等価です。.
-
typing.Callable¶ 呼び出し可能型;
Callable[[int], str]は (int) -> str の関数です。The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list must be a list of types or an ellipsis; the return type must be a single type.
There is no syntax to indicate optional or keyword arguments; such function types are rarely used as callback types.
Callable[..., ReturnType](literal ellipsis) can be used to type hint a callable taking any number of arguments and returningReturnType. A plainCallableis equivalent toCallable[..., Any], and in turn tocollections.abc.Callable.
-
typing.ClassVar¶ クラス変数であることを示す特別な型構築子。
PEP 526 で導入された通り、 ClassVar でラップされた変数アノテーションによって、ある属性はクラス変数として使うつもりであり、そのクラスのインスタンスから設定すべきではないということを示せます。使い方は次のようになります:
class Starship: stats = {} # type: ClassVar[Dict[str, int]] # class variable damage = 10 # type: int # instance variable
ClassVarは型のみを受け入れ、それ以外は受け付けられません。ClassVar はクラスそのものではなく、
isinstance()やissubclass()で使うべきではありません。:data:`ClassVar`は Python の実行時の挙動を変えないことに注意してください。サードパーティの型検査器が使うことができるため、次のコードはそれらによってエラーとされるかもしれません:enterprise_d = Starship(3000) enterprise_d.stats = {} # Error, setting class variable on instance Starship.stats = {} # This is OK
バージョン 3.5.3 で追加.
-
typing.AnyStr¶ AnyStrは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
-
typing.TYPE_CHECKING¶ サードパーティーの静的型検査器が
Trueと仮定する特別な定数。 実行時にはFalseになります。使用例:if TYPE_CHECKING: import expensive_mod def fun(): local_var: expensive_mod.some_type = other_fun()
