TypedDict 类是需要 Dict 的函数的不兼容类型

rkr*_*r87 0 python mypy typeddict

我创建了下面的 TypedDict 类;

class Appinfo(TypedDict):
    appid: int
    extended: dict[str, Any]
    config: dict[str, Any]
    depots: dict[str, Any]
    ufs: dict[str, Any]

class SteamAppInfo(TypedDict):
    appid: int
    data: dict[str, Appinfo]
Run Code Online (Sandbox Code Playgroud)

在我的应用程序中,我将此类的变量传递给需要字典的函数;

    def dict_get_key_list(data: dict[str, Any], key_list: list[str]) -> Any:
        """returns a dict value or None based on list of nested dict keys provided"""
        try:
            return reduce(operator.getitem, key_list, data)
        except KeyError:
            return None
Run Code Online (Sandbox Code Playgroud)

代码本身运行良好,就所有意图和目的而言,SteamAppInfo 是一本字典。但是,MyPy 给我以下错误;

error: Argument 1 to "dict_get_key_list" of "Utils" has incompatible type "SteamAppInfo"; expected "Dict[str, Any]"
Run Code Online (Sandbox Code Playgroud)

如何让 MyPy 识别出传递的是字典,而不必列出我创建的所有 TypedDict 作为可能的变量类型或将变量类型设置为 Any?

Bar*_*mar 5

来自mypy 文档

对象TypedDict不是常规dict[...]类型的子类型(反之亦然),因为dict它允许添加和删除任意键,这与TypedDict. 但是,任何TypedDict对象都是 的子类型(即兼容)Mapping[str, object],因为Mapping只提供对字典项的只读访问:

所以使用data: Mapping[str, Any]而不是data: dict[str, Any].