【问题标题】:Mypy complains about incompatible type when variable type is subset of expected type当变量类型是预期类型的​​子集时,Mypy 抱怨类型不兼容
【发布时间】:2021-04-22 06:04:17
【问题描述】:

尝试构建一个xarrayDataset,我们在其中构建参数“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 吗?在任何情况下,Tuples 和 bools 不是 Any 类型吗?我对此处的 mypy 和/或 Python 类型提示有什么不明白的地方?

【问题讨论】:

  • 非常感谢!我看错了地方-这里的问题是(从您的评论中了解到)str 不被视为Hashable.. 或者一般来说,Mappings 中的键不是协变的,另请参阅@987654323 @
  • 我的理解是str Hashable,但由于dict 是可变数据类型,因此您必须为键传递完全相同的类型,不是子类型。被调用的函数可能会在传递的参数中添加另一个 Hashable 键,从而破坏源代码。
  • 是的,感谢您澄清这一点,我没有正确表达。

标签: python-3.x mypy python-typing


【解决方案1】:

使用来自Selcuk 的信息,我发现这个有点冗长的解决方案,如mypy docs 中所述:由于Mappings 的键是不变的,因此需要明确提示str 有输入Hashable。 (虽然字符串是Hashable 的子类型,Mappings 键不是协变的,不允许子类型。)。或者,正如Selcuk 所说的his comment

str Hashable,但由于dict 是可变数据类型,因此您必须为键传递完全相同的类型,而不是子类型。被调用的函数可能会在传递的参数中添加另一个 Hashable 键,从而破坏源代码。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    • 2021-05-08
    • 2022-06-14
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    相关资源
    最近更新 更多