我有一个带有多个默认值的 kwargs 的函数。其中之一(在中间某处)是一个控制返回类型的布尔切换。
我想为此方法创建两个重载,Literal[True/False]
但保留默认值。
我的想法如下:
from typing import overload, Literal
@overload
def x(a: int = 5, t: Literal[True] = True, b: int = 5) -> int: ...
@overload
def x(a: int = 5, t: Literal[False] = False, b: int = 5) -> str: ...
def x(a: int = 5, t: bool = True, b: int = 5) -> int | str:
if t:
return 5
return "asd"
但 mypy 提出:
错误:重载的函数签名 1 和 2 与不兼容的返回类型重叠
我认为那是因为x()
会发生冲突。
但是我无法删除= False
第二个重载中的默认值,因为它前面a
有带有默认值的 arg。
我怎样才能正确地超载这个
x()
→ int
x(t=True)
→int
x(t=False)
→str
这是一个老问题。原因是您在两个分支中都指定了默认值,因此在两个分支中x()
都是可能的,并且返回类型未定义。
对于这种情况,我有以下模式:
from typing import overload, Literal
@overload
def x(a: int = 5, t: Literal[True] = True, b: int = 5) -> int: ...
@overload
def x(a: int = 5, *, t: Literal[False], b: int = 5) -> str: ...
@overload
def x(a: int, t: Literal[False], b: int = 5) -> str: ...
def x(a: int = 5, t: bool = True, b: int = 5) -> int | str:
if t:
return 5
return "asd"
为什么以及如何?您必须考虑调用函数的方法。首先,您可以提供a
,然后t
可以作为 kwarg (#2) 或 arg (#3) 给出。您也可以保留a
默认值,然后t
始终是一个 kwarg(再次 #2)。这是为了防止将 arg 放在 kwarg 之后,即SyntaxError
. 对多个参数进行重载比较困难,但也可以采用这种方式:
@overload
def f(a: int = 1, b: Literal[True] = True, c: Literal[True] = True) -> int: ...
@overload
def f(a: int = 1, *, b: Literal[False], c: Literal[True] = True) -> Literal['True']: ...
@overload
def f(a: int = 1, *, b: Literal[False], c: Literal[False]) -> Literal['False']: ...
@overload
def f(a: int, b: Literal[False], c: Literal[True] = True) -> Literal['True']: ...
@overload
def f(a: int, b: Literal[False], c: Literal[False]) -> Literal['False']: ...
def f(a: int = 1, b: bool = True, c: bool = True) -> int | Literal['True', 'False']:
return a if b else ('True' if c else 'False') # mypy doesn't like str(c)
你可以在这里玩重载。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句