我正在尝试使用抽象基类来编写 Python 的类型注释来编写一些接口。有没有办法注释和的可能*args
类型**kwargs
?
例如,如何表示函数的合理参数是一个int
或两个int
s?type(args)
给出了Tuple
所以我的猜测是将类型注释为Union[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]]"
mypy 不喜欢函数调用是有道理的,因为它希望tuple
调用本身有 a 。解包后的添加也给出了我不明白的打字错误。
如何注释 和 的合理*args
类型**kwargs
?