0
0

More than 1 year has passed since last update.

Python 3 Typing 早見

Posted at

書きかけ。
知りたい typing の書き方があったらコメントしていただければ調べます。

入門

変数に使う

hoge: int = 1

変数を宣言せずに type hint だけ書くこともできる。

hoge: int

宣言したように見えるが呼び出すと not defined となる。

関数の返り値に使う

def fuga(hoge: str) -> bool:
    return True

基本

リスト

__list: list[str]

辞書

__dict: dict[str, str]

全てを受け入れる型 Any

from typing import Any

anyyyyy: Any

複数の型

from typing import Union

hoge: Union[int, str] = 1
hoge: int | str = 1  # python 3.10

決められた値のみ許可

from typing import Literal

hoge: Literal['hoge', 'hoge2', 2, False] = 'hoge'

応用

引数の型によって返り値の型を変える その1(overload)

from typing import overload

@overload
def fuga(hoge: int, piyo: int) -> int: ...
@overload
def fuga(hoge: int) -> None: ...


def fuga(hoge: int, piyo: int | None = None) -> int | None:
    if piyo is None:
        return None
    else:
        return hoge + fuga

引数の型によって返り値の型を変える その2(TypeVar)

from typing import TypeVar

_HogeType = TypeVar('_HogeType')


def fuga(hoge: _HogeType) -> _HogeType:
    return hoge

TypeVarに入ることのできる型を限定することもできる。

from typing import TypeVar

_HogeType = TypeVar('_HogeType', HogeClass, FugaClass)

クラスそのもの(インスタンスではない)を型アノテーションに指定

hoge: type = HogeClass

でも良いが...

from typing import Type

hoge: Type[HogeClass] = HogeClass

と書くこともできる。TypeVarとの組み合わせが便利。

from typing import Type, TypeVar, Any

_HogeType = TypeVar('_HogeType')


def fuga(hoge: Type[_HogeType], __dict: dict[str, Any]) -> _HogeType:
    return hoge(**__dict)

関数fugaの引数で与えられたクラスに応じて、返り値の型もそのクラスのインスタンスになる。

決められたキーのみを持つ辞書

from typing import TypedDict

class HogeDict(TypedDict):
    hoge: str
    fuga: int
    piyo: bool

__dict: HogeDict

自身と同じクラスを返すメソッド (python 3.11)

class HogeClass():
    def hogehoge(self) -> HogeClass:  # NameError: name 'HogeClass' is not defined
        return HogeClass()

これは not defined エラーとなる。なので typing.Self を使う。

from typing import Self

class HogeClass():
    def hogehoge(self) -> Self:
        return HogeClass()
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0