带类型化键的字典的联合,与空字典不兼容



我想键入一个字典,其中所有的键都是整数或字典中所有的键都是字符串。

然而,当我读取mypy (v0.991)对以下代码:

from typing import Union, Any
special_dict: Union[dict[int, Any], dict[str, Any]]
special_dict = {}

我得到一个Incompatible types错误。

test_dict_nothing.py:6: error: Incompatible types in assignment (expression has type "Dict[<nothing>, <nothing>]", variable has type "Union[Dict[int, Any], Dict[str, Any]]")  [assignment]
Found 1 error in 1 file (checked 1 source file)

如何表达我的输入意图。

这是一个mypy错误,在这里已经报告了优先级为1的错误。有一个简单的解决方法:

from typing import Any
special_dict: dict[str, Any] | dict[int, Any] = dict[str, Any]()

这段代码类型检查成功,因为你基本上给了mypy一个更具体的字典类型的提示。它可以是任何匹配类型,并且不会影响进一步的检查,因为您使用显式类型提示扩展了最终类型。

最新更新