【发布时间】: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