我正在尝试使用抽象基类的Python类型注释来编写一些接口.有没有办法注释可能的类型*args
和**kwargs
?
例如,如何表达函数的合理参数是一个int
还是两个int
?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))
Run Code Online (Sandbox Code Playgroud)
来自mypy的错误消息:
t.py: note: In function "foo":
t.py:6: error: Unsupported operand types for + ("tuple" and "Union[Tuple[int, int], Tuple[int]]") …
Run Code Online (Sandbox Code Playgroud)