所描述的情况是overloading的典型用例.
您可以对函数进行注释,使True
参数返回3元组,False
-2元组返回:
from typing import overload, Literal
@overload
def func(third: Literal[True]) -> tuple[int, int, int]:
...
@overload
def func(third: Literal[False] = ...) -> tuple[int, int]:
...
def func(third: bool = False) -> tuple[int, int] | tuple[int, int, int]:
if third:
return 1, 2, 3
else:
return 1, 2
a, b, c = func(True)
a, b = func(False)
a, b = func()
Playground
当前代码中的问题是mypy
不知道返回类型是2元组还是3元组.它不会对实现进行额外的假设,类型提示是严格的.您的代码可能如下所示(mypy
以完全相同的方式解释):
import random
def func(three: bool = False) -> tuple[int, int] | tuple[int, int, int]:
if random.random() < 0.5:
return 1, 1
else:
return 1, 1, 1
a, b, c = func()
...现在,您的代码在(大约)50%的情况下会失败,并且mypy
%指向该错误.