いくつかのインターフェイスを作成するために、抽象基本クラスを使用して Python の型注釈を試しています。と の可能なタイプに注釈を付ける方法は*argsあり**kwargsますか?
たとえば、関数への適切な引数が 1 つintまたは 2 つintの s であることをどのように表現しますか? 私の推測では、タイプに として注釈を付けることでしtype(args)たが、これは機能しません。TupleUnion[Tuple[int, int], Tuple[int]]
from typing import Union, Tuple
def foo(*args: Union[Tuple[int, int], Tuple[int]]):
try:
i, j = args
return i + j
except ValueError:
assert len(args) == 1
i = args[0]
return i
# ok
print(foo((1,)))
print(foo((1, 2)))
# mypy does not like this
print(foo(1))
print(foo(1, 2))
mypy からのエラー メッセージ:
t.py: note: In function "foo":
t.py:6: error: Unsupported operand types for + ("tuple" and "Union[Tuple[int, int], Tuple[int]]")
t.py: note: At top level:
t.py:12: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:14: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:15: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:15: error: Argument 2 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
tuple呼び出し自体に a があることを期待しているため、mypy が関数呼び出しに対してこれを好まないのは理にかなっています。解凍後の追記もよくわからないタイプミス。
*argsとの適切な型にどのように注釈を付けるの**kwargsですか?