使字典绑定 TypeVar 接受 TypedDict

Making a dict bound TypeVar accept TypedDict

我有一个通用函数,它接受任何字典和 returns 具有相同结构的字典。

from typing import TypeVar
from typing_extensions import TypedDict

DictT = TypeVar("DictT", bound=dict)

def myfunc(d: DictT) -> DictT:
    return d

TD = TypedDict("TD", {
    "b": int,
})
b: TD = {
    "b": 2,
}
myfunc(b)

当我用字典调用它时它通过了 mypy,但是当我用 TypedDict 调用函数时我从 mypy 得到一个错误

16: error: Value of type variable "DictT" of "myfunc" cannot be "TD"

为什么 TD 不被绑定接受,我该如何使这些类型正常工作?

在 MyPy here 中有关于此功能的公开票证。目前,简短的版本是;你做不到,你能做的最好的事情就是让你的类型 Mapping[Any, Any]。如果您需要 dict 的更多功能而不是 Mapping 属性,您可以尝试 Protocol.