Python 中可变嵌套 Dict 的类型提示

5t4*_*4c3 9 python type-hinting python-typing

由于我在 Python 中经常使用类型提示,因此我遇到了递归函数接受dict,str作为键和intdict作为值 ( Dict[str, Union[int, Dict[...]]) 的场景。此时的问题是可能的dict-value 也有str作为键和intdict作为值 ( Dict[str, Union[int, Dict[Dict[str, Union[int, Dict[...]]]])。

但是,我不知道传递的字典有什么深度。是否有可能通过类型提示来可视化这种重复模式?

Ale*_*ood 7

渴望的语法是这样的:

\n
RecursiveDict = Dict[str, Union[\'RecursiveDict\', int]]\n
Run Code Online (Sandbox Code Playgroud)\n

截至目前,MyPy(以及大多数其他 Python 类型检查器)不支持此语法 \xe2\x80\x94要求支持递归类型的MyPy错误报告已公开 6 年。然而,一些替代类型检查器最近引入了对递归注释的支持。所以,这有点鱼龙混杂。

\n

也可以看看:

\n\n

  • 根据 https://github.com/python/mypy/pull/13297 现在支持它。 (2认同)