我正在试用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))
来自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
.解包后添加的内容也会导致一个我不理解的输入错误.
如何为*args
和**kwargs
注释合理的类型?