最佳答案
我正在尝试使用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))
来自myypy的错误消息:
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]]"
myypy不喜欢函数调用这样做是有道理的,因为它期望在调用本身中有tuple
。unpacking后的添加也给出了一个我不理解的输入错误。
如何注释*args
和**kwargs
的合理类型?