Python 中可变嵌套 Dict 的类型提示 [英] Type hints for variably-nested Dict in Python
问题描述
因为我在 Python 中经常使用类型提示,所以我遇到了这样一种情况:递归函数接受 dict
,以 str
作为键和 int
或 dict
作为值 (Dict[str, Union[int, Dict[...]]
).此时的问题是可能的 dict
-value 也有 str
作为键和 int
或 dict
作为值 (Dict[str, Union[int, Dict[Dict[str, Union[int, Dict[...]]]]]
).
Since I'm working a lot with type hints in Python I came across the scenario that a recursive function accepts dict
, with str
as keys and int
or dict
as value (Dict[str, Union[int, Dict[...]]
). The problem at this point is that the possible dict
-value has also str
as keys and int
or dict
as value (Dict[str, Union[int, Dict[Dict[str, Union[int, Dict[...]]]]
).
但是,我不知道传递的字典有什么深度.是否有可能通过类型提示将这种重复模式可视化?
However, I don't know which depth the passed dictionary has. Is there any possibility to visualize this repetitive pattern with type hints?
推荐答案
向往的语法类似于:
RecursiveDict = Dict[str, Union['RecursiveDict', int]]
截至目前,MyPy 不支持此语法 — 错误报告要求支持递归类型已经开放了 6 年.但是,一些替代类型检查器 最近引入了对递归注释的支持.所以,这有点好坏参半.
As of now, MyPy doesn't support this syntax — the bug report asking for support for recursive types has been open for 6 years. However, some alternative type-checkers have recently introduced support for recursive annotations. So, it's a bit of a mixed bag.
另见:
这篇关于Python 中可变嵌套 Dict 的类型提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!