gpt4 book ai didi

python - 递归类型注释

转载 作者:行者123 更新时间:2023-12-01 01:22:51 26 4
gpt4 key购买 nike

我正在尝试在适用的情况下将静态类型注释引入我的代码库。一种情况是读取 JSON 时,生成的对象将是一个由字符串作为键的字典,其值具有以下类型之一:

  • bool
  • str
  • float
  • 整数
  • 列表
  • 字典

但是上面的 listdict 可以包含相同类型的字典,从而导致递归定义。这可以在 Python3 的类型结构中表示吗?

最佳答案

从 mypy 0.990 开始,mypy 最终支持递归类型注释,使用自然语法:

from typing import Union, Dict, List

JSONVal = Union[None, bool, str, float, int, List['JSONVal'], Dict[str, 'JSONVal']]

d: JSONVal = {'a': ['b']}

mypy 输出:

Success: no issues found in 1 source file

在 0.990 之前,这会产生一个错误,报告缺乏递归类型支持:

$ mypy asdf.py
asdf.py:3: error: Recursive types not fully supported yet, nested types replaced with "Any"

在此类版本中,Dict[str, Any] 将是最佳选择。

<小时/>

您现在还可以使用相互递归类型别名,这样您就可以执行类似的操作

from typing import Union, Dict, List

JSONVal = Union[None, bool, str, float, int, 'JSONArray', 'JSONObject']
JSONArray = List[JSONVal]
JSONObject = Dict[str, JSONVal]

d: JSONObject = {'a': ['b']}

关于python - 递归类型注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53638973/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com