Skip to content Skip to sidebar Skip to footer

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 v

Solution 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 importUnion, 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.

Post a Comment for "Recursive Type Annotations"