递归类型注解 [英] Recursive type annotations
问题描述
我正在尝试在适用的情况下向我的代码库引入静态类型注释.一种情况是在读取 JSON 时,结果对象将是一个以字符串为键的字典,具有以下类型之一的值:
I'm trying to introduce static type annotations to my codebase where applicable. One case is when reading a JSON, the resulting object will be a dictionary keyed by strings, with values of one of the following types:
bool
str
浮动
int
list
dict
然而,上面的 list
和 dict
可以包含相同类型的字典,导致递归定义.这在 Python3 的类型结构中可以表示吗?
However the list
and dict
above can contain that same sort of dictionary, leading to a recursive definition. Is this representable in Python3's type structure?
推荐答案
从 mypy 0.641 开始,mypy 不支持您正在寻找的那种递归类型注释.自然语法:
As of mypy 0.641, mypy doesn't support the sort of recursive type annotation you're looking for. The natural syntax:
from typing import Union, Dict, List
JSONVal = Union[None, bool, str, float, int, List['JSONVal'], Dict[str, 'JSONVal']]
d: JSONVal = {'a': ['b']}
产生错误报告缺乏递归类型支持:
produces an error reporting a lack of recursive type support:
$ mypy asdf.py
asdf.py:3: error: Recursive types not fully supported yet, nested types replaced with "Any"
另请参阅关于递归类型支持的 mypy 问题跟踪器线程.
Also see the mypy issue tracker thread on recursive type support.
就目前而言,Dict[str, Any]
可能是要走的路.
For now, Dict[str, Any]
is probably the way to go.
这篇关于递归类型注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!