我正在尝试使用抽象基类的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) 如何为所有这些可调用对象指定一种类型:
a(str)
b(str, str)
c(str, str, str)
d(str, str, str, str
Run Code Online (Sandbox Code Playgroud)
我发现我可以Callable[..., None]用一般方式指定,但如何详细指定所有参数都将是 str 而不使用丑陋的语法Union[Callable[[str], None], Callable[[str, str], None, __more_like_this__]。有其他方法可以做到吗?我可以通过使用打字来做到吗?