Mypy:与函数字典不兼容的类型(对象)

Mypy: Incompatible type (object) with a dictionary of functions

以下代码:

from typing import Union

def a() -> int:
    return 1

def b() -> str:
    return 'a'

def c(arg: str = 'a') -> Union[int, str]:
    return {'a': a, 'b': b}[arg]()

触发以下 mypy 异常:

error: Incompatible return value type (got "object", expected "Union[int, str]")

解决方法是使用:

return a() if arg == 'a' else b()

在这种情况下 Mypy 不会报错,但如果函数超过 2 个,字典语法仍然有用。 有解决办法吗,还是 Mypy 的错误?

我认为问题在于您没有声明允许的字典类型。尽管在您的代码中很清楚字典中只有两种类型的输出,但从打字的角度来看,没有什么可以阻止向其中添加另一个函数 d()

您可以尝试以下方法来解决此问题:

from typing import Union, Dict, Callable

output_dictionary : Dict[str, Union[Callable[[], int],Callable[[], str]]] = {'a': a, 'b': b}

def c(arg: str = 'a') -> Union[int, str]:
    return output_dictionary[arg]()