【问题标题】:Mypy: Incompatible type (object) with a dictionary of functionsMypy:与函数字典不兼容的类型(对象)
【发布时间】:2019-02-12 12:56:38
【问题描述】:

以下代码:

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 错误?

【问题讨论】:

    标签: python mypy


    【解决方案1】:

    我认为问题在于您没有声明允许的字典类型。尽管在您的代码中很清楚字典中只有两种类型的输出,但从打字的角度来看,没有什么可以阻止将另一个函数 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]()
    

    【讨论】:

      猜你喜欢
      • 2019-06-18
      • 2022-06-14
      • 2021-09-26
      • 2021-05-09
      • 1970-01-01
      • 2018-04-21
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      相关资源
      最近更新 更多