我正在尝试使用具有抽象基类的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
调用本身中包含a。解压后的附加内容还会产生我不理解的输入错误。
一个人如何诠释明智的类型*args
和**kwargs
?
Optional
?Python有什么变化吗?还是您改变了主意?由于None
默认值,是否仍非严格必要?