当变量类型是预期类型的​​子集时,Mypy 抱怨类型不兼容

Mypy complains about incompatible type when variable type is subset of expected type

尝试构建一个 xarray Dataset,我们在将其传递给构造函数之前构建参数“coords”和“attrs”的输入:

coordinates = {"time": ("time", time_coordinates)}
attributes = {"some_flag": False}
...
ds = xr.Dataset(data_vars=variables, coords=coordinates, attrs=attributes)

令我困惑的是 mypy 运行 针对此代码的输出:

error: Argument "coords" to "Dataset" has incompatible type "Dict[str, Tuple[str, Any]]"; expected "Optional[Mapping[Hashable, Any]]"
error: Argument "attrs" to "Dataset" has incompatible type "Dict[str, bool]"; expected "Optional[Mapping[Hashable, Any]]"

dict 不是 Mapping 吗? str 不也是 Hashable 吗?无论如何,Tuplebool 不是 Any 类型吗?关于 mypy and/or Python 类型提示,我有什么不明白的地方?

使用来自 Selcuk, I found this somewhat verbose solution, as detailed in the mypy docs: As the keys of Mappings are invariant, one needs to hint explicitly that the str there is of type Hashable. (While strings are a subtype of Hashable, Mappings keys are not covariant, disallowing subtypes.). Or, as Selcuk puts it in 的信息:

str is a Hashable, but since dict is a mutable data type you must be passing the exact same type for the keys, not a subtype. There is a possibility that the called function might add another Hashable key to the passed argument, breaking the source.

coordinates: Dict[Hashable, Tuple[str, Any]] = {
    "time": ("time", time_coordinates)
}
attributes: Dict[Hashable, Any] = {"some_flag": False}