MyPy 错误:返回值类型不兼容(得到“Union[X, Y]”,预期为“X”)

问题描述 投票:0回答:1

我有2个功能

func_1
func_2
func_1
期望返回类型 X,而
func_2
期望返回
Union[X, Y]

from typing import Union

def func_2(...) -> Union[X, Y]:
    ...

def func_1(...) -> X:
    return func_2(...)

当我们在此代码片段上使用 MyPy 时,我们会发现它报告以下内容:

Incompatible return value type (got "Union[X, Y]", expected "X")

请注意,

func_2
必须返回两种类型之一,唯一的方法是将其拆分为两个不同的函数,它们执行相同的操作,但每个函数返回单一类型。如果可能的话我想避免这种情况。

为什么 MyPy 会抛出这个错误?我怎样才能克服它而不重复自己?

python type-hinting mypy python-typing
1个回答
0
投票

您可以使用

isinstance()
检查来消除 Union 类型的歧义。

因此,对于您的示例代码,类似于:

from typing import Union

def func_2(...) -> Union[X, Y]:
    ...

def func_1(...) -> X:
    output = func_2(...)
    if isinstance(output, Y):
        ... # do something to handle the Y type here, raise, convert etc.
    return output
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.