示例如下,需要确保 IDE 类型检查器或
reveal_type
能够正确识别 k
、j
和 i
类型。
也许有某种方法可以建议输入
args
是空 tuple
和 kwargs
空 dict
,然后返回值将是 tuple[int]
?
from typing import Union, overload
def test(*args: int, **kwargs: str) -> Union[int, str, tuple[int]]:
if args:
return 5
if kwargs:
return "5"
return (5,)
# now all are Union[int, str, tuple[int]]
k = test(1)
j = test(i="1")
i = test()
reveal_type(k) # should be int
reveal_type(j) # should be str
reveal_type(i) # should be tuple[int]
这是一个部分解决方案,至少允许 mypy 推断
k
、j
和 i
的正确类型。所需的签名基本上是重叠的,所以我不确定是否可以对过载重叠错误采取任何措施。
from typing import Union, overload
@overload
def test() -> tuple[int]: # type: ignore[overload-overlap]
...
@overload
def test(*args: int) -> int: # type: ignore[overload-overlap]
...
@overload
def test(**kwargs) -> str:
...
def test(*args: int, **kwargs: str) -> Union[int, str, tuple[int]]:
if args:
return 5
if kwargs:
return "5"
return (5,)
# now all are Union[int, str, tuple[int]]
k = test(1)
j = test(i="1")
i = test()
reveal_type(k) # should be int
reveal_type(j) # should be str
reveal_type(i) # should be tuple[int]
mypy v1.9.0 输出(在线尝试!):
main.py:29: note: Revealed type is "builtins.int"
main.py:30: note: Revealed type is "builtins.str"
main.py:31: note: Revealed type is "tuple[builtins.int]"
Success: no issues found in 1 source file