【问题标题】:Type hint for nested dict嵌套字典的类型提示
【发布时间】:2020-02-12 11:48:20
【问题描述】:

我在 Python 脚本中解析的那种数据结构是一个 json 文件,它在json.load(file_handle) 之后是<class 'dict'> 类型。到目前为止,一切都很好。现在对于使用它作为输入参数的函数,我想要解析的 json 的类型提示。我在typing documentation 中读到,对于dicts 作为参数,我应该使用Mapping[key_type, value_type]

from typing import Mapping

def foo(json_data: Mapping[str, str]) -> None:
    ...

我解析的 json 有 str-type 键和 str-type 值,但通常情况下,它的结构是高度递归的。因此,一个值更可能是带有str 键的dict,甚至是dicts 作为值。它是非常嵌套的,直到在最深层次上,最后一个 dict 最终具有 str 键和 str 值。

那么如何更精确地表示这个数据结构呢?我在想一些事情,类似于this question,它可能是:

Union[Mapping[str, str], Mapping[str, Mapping]]

但它似乎只代表了一层递归。有没有更好的方法来输入提示?

【问题讨论】:

标签: python json dictionary type-hinting


【解决方案1】:

简单的字典

您可以简单地使用Mapping[K, V] 作为另一个Mapping 的值。假设你的 json 看起来像这样:

{
   "person_1": {"money": 1000},
   "person_2": {"money": 1000}
}

在这种情况下,您可以使用如下所示的类型提示:

Mapping[str, Mapping[str, int]]

更难的字典

但是假设你有更复杂的东西,像这样:

{
    "person_1": {
        "money": 1000,
        "job": "coder",
    }
}

那你怎么能输入提示呢?你可以使用Union(来自typing)来做这样的事情:

Mapping[str, Mapping[str, Union[str, int]]]

但是现在我们会遇到一个问题,比如 mypy 认为 our_dict["person_1"]["job"] 的类型是 Union[str, int]

好吧,这并没有错,毕竟这是我们告诉它的。 TypedDict 来自 typing_extensions

from typing_extensions import TypedDict

class Person(TypedDict):
    money: int
    job: str

# type hint you would use in your function:
Mapping[str, Person]

注意: 在 python 3.8 TypedDicttyping 的一部分

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多