如何键入注释通用嵌套 TypedDict?

问题描述 投票:0回答:0

我正在尝试从类似于以下的代码中删除

Any
类型提示:

from typing import TypedDict, Any


class NestedDict(TypedDict):
    foo: str


class EventDict(TypedDict):
    nested: NestedDict


class BaseEventDict(TypedDict):
    nested: Any # this should accept NestedDict but also other TypedDicts which may contain additional fields


test_dict: EventDict = {
    "nested": {"foo": "abc"},
}


def print_dict(source_dict: BaseEventDict):
    print(source_dict)


print_dict(test_dict)

由于

nested
字段可以包含
NestedDict
或其他带有附加字段的
TypedDict
s,我无法想出一个兼容的
TypedDict
mypy
抱怨额外的键)。我认为
Mapping[str, object]
可能会代替
Any
,因为 [A]ny TypedDict 类型与 Mapping[str, object] 一致。然而,
mypy
Argument 1 to "print_dict" has incompatible type "TopLevelDict"; expected "BaseDict"
抱怨。不确定我在这里错过了什么?

python python-3.x mypy typeddict
© www.soinside.com 2019 - 2024. All rights reserved.