Ada*_*ith 3 python typing python-3.x
我正在尝试在适用的情况下向我的代码库引入静态类型注释。一种情况是在读取 JSON 时,结果对象将是一个以字符串为键的字典,具有以下类型之一的值:
boolstrfloatintlistdict然而list,dict以上可以包含相同类型的字典,导致递归定义。这在 Python3 的类型结构中可以表示吗?
从 mypy 0.641 开始,mypy 不支持您正在寻找的那种递归类型注释。自然语法:
from typing import Union, Dict, List
JSONVal = Union[None, bool, str, float, int, List['JSONVal'], Dict[str, 'JSONVal']]
d: JSONVal = {'a': ['b']}
Run Code Online (Sandbox Code Playgroud)
产生错误报告缺乏递归类型支持:
$ mypy asdf.py
asdf.py:3: error: Recursive types not fully supported yet, nested types replaced with "Any"
Run Code Online (Sandbox Code Playgroud)
另请参阅有关递归类型支持的mypy 问题跟踪器线程。
目前,Dict[str, Any]可能是要走的路。