问题
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