Skip to content

2023 06 24

typing.overload

https://docs.python.org/ja/3/library/typing.html#typing.overload - @overloadデコレータで関数・メソッドの多重定義をできる - 複数の@overloadデコレータ付きの関数群+デコレータ無しの本体の実装が必要 - 実行時には影響なし、型チェックの時のみ意味を持つ。

@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 goes here

.pyiファイル

インテーフェース定義ファイル。 Pythonで型チェックを行うmypyライブラリが型情報を記録しておくファイル。 .pyファイルには型情報なしで.pyiファイルに型情報を記載することができる。

# test.pyi
from typing import overload, TypeVar

T = TypeVar("T", int, float)

@overload
def test(val: int) -> int: ...

@overload
def test(val: float) -> float: ...
# test.py
def test(val):
    return val * 10
# main.py
from test import test

test("")
> mypy .\main.py
Success: no issues found in 1 source file
PS C:\github\atcoder> mypy .\main.py
main.py:3: error: No overload variant of "test" matches argument type "str"
main.py:3: note: Possible overload variants:
main.py:3: note:     def test(val: int) -> int
main.py:3: note:     def test(val: float) -> float
Found 1 error in 1 file (checked 1 source file)

「...」(Ellipsisオブジェクト)

https://docs.python.org/ja/3/library/constants.html#Ellipsis

Ellipsis リテラル "..." と同じです。 主に拡張スライス構文やユーザ定義のコンテナデータ型において使われる特殊な値です。Ellipsis が types.EllipsisType 型の唯一のインスタンスです。

特に利用方法は指定されていない。 bool(...)はTrueを返す。 基本的には何らかの省略を表すときに使われる。@overloadの型定義等。