Recursive type annotations

喜夏-厌秋 提交于 2020-02-15 06:37:09

问题


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
  • float
  • int
  • list
  • dict

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?


回答1:


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"

Also see the mypy issue tracker thread on recursive type support.

For now, Dict[str, Any] is probably the way to go.



来源:https://stackoverflow.com/questions/53638973/recursive-type-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!