Recursive type annotations

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:

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?


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 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.