[英]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不会抱怨,但如果有两个以上的函数,那么dictionnary语法仍然有用。 有没有办法,或者它是一个Mypy bug?
我认为问题在于您没有声明允许的字典类型。 虽然在你的代码中很明显,字典中只有两种类型的输出,但从输入的角度来看,没有什么能阻止另一个函数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]()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.