【问题标题】:Python static typing: Annotating multiple returns typesPython 静态类型:注释多个返回类型
【发布时间】:2022-11-15 09:59:46
【问题描述】:

简而言之,我有一个返回 int 或 float 的函数。然后调用函数检查第一个函数的返回类型,如果是 float 则返回 -1,否则返回原始值,因为它必须是 int。

# pseudo code for the aforementioned 

def f1(*args, **kwargs) -> int | float: ... 

def f2(*args, **kwargs) -> int:
    ans = f1(...)
    if type(ans) == float:
        return -1
    return ans  # the idea here is that if f1 does not return float, it must return an int which is a valid return for f2

我的静态检查器因以下错误而失败

Expression of type "int | float" cannot be assigned to return type "int"
  Type "int | float" cannot be assigned to type "int"
    "float" is incompatible with "int"

错误信息非常直接,f1 返回 int 或 float,因为 f2 期望返回 int,所以不能直接返回 f1 的结果。但是,(理想情况下)我的 if 语句可以防止 f1 的结果是浮点数的可能性。

有谁知道更好的方法来注释以下内容。我目前正在使用类型:忽略标志,但我不希望使用此解决方法。

【问题讨论】:

  • 你的 Python 版本是什么?
  • 在这个环境中,它是 Python 3.9.13。但我对 3.10.6 也有同样的问题

标签: python annotations mypy


【解决方案1】:

您需要与isinstance联系:

def f1(*args, **kwargs) -> int | float: ... 

def f2(*args, **kwargs) -> int:
    ans = f1(...)
    if isinstance(ans) == float:
        return -1
    # now the typechecker can infer the type of 'ans' as int
    return ans 

更多信息Mypy documentation

【讨论】:

    猜你喜欢
    • 2017-03-04
    • 2017-03-15
    • 2011-08-03
    • 2019-02-15
    • 2019-07-11
    • 2016-09-10
    • 2017-02-10
    相关资源
    最近更新 更多