python - MyPy 不允许将 TypedDict 的类作为参数传递给函数

原文 标签 python mypy


class A(TypedDict):
    abc: str

class B(TypedDict):
    xyz: str

def func(dict_class: Union[type[A], type[B]]) -> None:

导致以下 MyPy 错误:
error: Argument 1 to "func" has incompatible type "Type[A]"; expected "Union[Type[A], Type[B]]"
有没有其他方法可以告诉 MyPy dict_class参数只能是指定类型的字典类型?我知道我可以将类型提示更改为更通用的内容,这样 MyPy 就不会提示,但我真的不想。
更重要的是 PyCharm IDE 似乎可以很好地处理这个示例。那么它是 MyPy 的错误吗?


这是使用 TypedDict 时的已知问题例如提到的 here .

from typing import TypedDict

D = TypedDict('D', {})
x: type[D] = D  # error
error: Incompatible types in assignment (expression has type "Type[D]", variable has type "Type[D]")
@ilevkivskyi 解释了这种行为 here这边走:

Yeah, this doesn't work because Type[...] is not supposed to work with anything but classes, unions of classes, and Any, see PEP 484.

It seems to me it might be possible to relax this limitation to some extent, but first of all we should fix the errors message, which is cryptic.

您可以阅读有关使用 TypedDict 的更多信息在 PEP 589 . @serhiy.storchaka 简要描述了它 here如下:

TypeDict is a callable, it can be used as

Point2D = TypedDict('Point2D', x=int, y=int, label=str)

It can also be used as a base in class definition, but is is not a class itself. It does not occur in __bases__ of the created class, and it cannot be used in isinstance() and issubclass() checks. It is just yet one weird way to customize class creation.

关于python - MyPy 不允许将 TypedDict 的类作为参数传递给函数,我们在Stack Overflow上找到一个类似的问题:


python-3.x - 检查 Python 中的类型提示覆盖率

python - mypy:为什么 "int"是 "float"的子类型?

python - 如何为 Mypy 类型注释指定 OrderedDict K、V 类型?

python - 处理 Python 数学运算的准确性

python - 计算事件之间的时间差

python - 如何在不明确列出类型的情况下确保参数具有相同的类型?

python - 将类型指定为数字列表(整数和/或浮点数)?

python - Tornado RPi 不工作

python - 使用数组存储窗口的像素

python - 将RGB图像转换为棕褐色滤镜的公式是什么?