在 Python 中键入可变嵌套字典的提示
Type hints for variably-nested Dict in Python
因为我在 Python 中经常使用类型提示,所以我遇到了递归函数接受 dict
、str
作为键和 int
或 dict
作为值 (Dict[str, Union[int, Dict[...]]
)。此时的问题是可能的 dict
值也有 str
作为键和 int
或 dict
作为值 (Dict[str, Union[int, Dict[Dict[str, Union[int, Dict[...]]]]
).
但是,我不知道传递的字典有多深。有没有可能用类型提示来可视化这种重复模式?
渴望的语法是这样的:
RecursiveDict = Dict[str, Union['RecursiveDict', int]]
截至目前,MyPy(以及大多数其他 Python 类型检查器)不支持此语法 — MyPy bug report asking for support for recursive types has been open for 6 years. However, some alternative type-checkers have recently 引入了对递归注释的支持。所以,它有点鱼龙混杂。
另请参阅:
因为我在 Python 中经常使用类型提示,所以我遇到了递归函数接受 dict
、str
作为键和 int
或 dict
作为值 (Dict[str, Union[int, Dict[...]]
)。此时的问题是可能的 dict
值也有 str
作为键和 int
或 dict
作为值 (Dict[str, Union[int, Dict[Dict[str, Union[int, Dict[...]]]]
).
但是,我不知道传递的字典有多深。有没有可能用类型提示来可视化这种重复模式?
渴望的语法是这样的:
RecursiveDict = Dict[str, Union['RecursiveDict', int]]
截至目前,MyPy(以及大多数其他 Python 类型检查器)不支持此语法 — MyPy bug report asking for support for recursive types has been open for 6 years. However, some alternative type-checkers have recently 引入了对递归注释的支持。所以,它有点鱼龙混杂。
另请参阅: