gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:47:58 25 4
gpt4 key购买 nike

以下代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com