Can you define recursive type hints in Python?

Viewed 72

I have an alias for a type in Python:

from typing import Tuple, Dict, Union

SelectedModelArgs = Dict[
    str,
    Union[
        str,
        float,
        Tuple[float, float],
        Dict[str, Union[str, float, Tuple[float, float]]],
    ],
]

At present this allows for a dictionary with str to str, float, a tuple of floats or a nested dictionary of the same type. Is there a way to define this recursively to allow arbitrary nesting?

e.g.

SelectedModelArgs = Dict[
    str,
    Union[
        str,
        float,
        Tuple[float, float],
        SelectedModelArgs,
    ],
]

When I try this I get IDE errors:

  • Pylance: "SelectedModelArgs" is not defined
  • Mypy: Cannot resolve now "SelectedModelArgs" (possible cyclic definition)

Adding from __future__ import annotations to the top of the file does not resolve these (as it does with using a class name within a class definition).

I have also tried using the code example above but with the nested "SelectedModelArgs" as a string (as noted in this answer). This resolves the pylance error, but not the mypy error.

0 Answers
Related