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:
    print(dict_class.__annotations__)


func(A)
导致以下 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上找到一个类似的问题: https://stackoverflow.com/questions/69674078/

相关文章:

python - 在不知道键的情况下访问 python dict() 的值

python - 替代Python中的类对象

python - 当类型应该清晰时,如何处理 mypy 中不支持的操作数类型?

python - 设置默认参数的 mypy call-arg 错误

python - 在 python 中格式化 nan float

python - collect_list 通过保留基于另一个变量的顺序

python - 登录 Django 和 gunicorn

python - 从声明返回 "str"的函数返回 Any,同时返回 Dict val

python - 将生成器函数注释为迭代器的混淆

python - Pandas DataFrame mypy 错误 : slice index must be an integer or None