如何使用多个可选参数对函数进行类型重载?

M.尼克拉斯

我有一个带有多个默认值的 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用可选参数创建Python函数?

使用可选参数的方法重载

如何在rust中使用参数重载或可选参数?

如何使用可选参数调用python函数

flowtype:如何按参数计数/类型重载函数返回类型?

使用可选参数区分f#重载函数

如何给相同类型的多个函数参数?

如何使用相同的参数类型重载函数但其中一个可以为空

如何将多个函数重载作为单个参数传递?

带有多个不同类型的可选参数的调用函数

TypeScript允许使用可选参数-重载方法

如何使用可变参数重载函数

模板类型推导如何使用重载函数作为参数

使用重载机制而不是可选参数

如何停止Kotlin从一个带有可选参数的Kotlin函数中创建多个重载Java方法

类中的重载!=函数允许使用哪些参数类型

如何使用可选参数重载TypeScript中的函数?

Typescript函数重载,通用可选参数

基于可选参数存在的Typescript函数返回类型,而不使用函数重载

如何使用需要多个参数的键函数进行排序?

如何重载具有多个参数的函数?C ++

如何在TypeScript中使用泛型在重载函数中进行类型转换

使用out和可选参数进行方法重载

使用第一个可选参数进行重载

使用GCC在C中进行函数重载-具有多个参数的函数

如何为只有可选参数的函数定义多个重载?

如何使函数参数可选?

如何使用通用输入类型和多个/可选输入参数制作函数

c++ 多个重载函数实例匹配参数类型