【发布时间】:2016-08-30 03:20:41
【问题描述】:
我正在尝试使用抽象基类来编写 Python 的类型注释来编写一些接口。有没有办法注释*args 和**kwargs 的可能类型?
例如,如何表示函数的合理参数是一个int 或两个ints? 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 的合理类型?
【问题讨论】:
标签: python type-hinting python-typing