8

Since I'm working a lot with type hints in Python I came across the scenario that a recursive function accepts dict, with str as keys and int or dict as value (Dict[str, Union[int, Dict[...]]). The problem at this point is that the possible dict-value has also str as keys and int or dict as value (Dict[str, Union[int, Dict[Dict[str, Union[int, Dict[...]]]]).

However, I don't know which depth the passed dictionary has. Is there any possibility to visualize this repetitive pattern with type hints?

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
5t4cktr4c3
  • 151
  • 1
  • 10
  • See also [How can I type-hint a nested object in Python?](https://stackoverflow.com/questions/59498869/how-can-i-type-hint-a-nested-object-in-python) – ggorlen Jun 28 '21 at 17:37
  • Does this answer your question? [How to define a generic type that is not a class?](https://stackoverflow.com/questions/66363364/how-to-define-a-generic-type-that-is-not-a-class) – MisterMiyagi Jun 28 '21 at 17:46
  • 2
    I'm afraid it doesn't. What I mean is that my dict could had a depth from 0 to infinite. So basically what I want is a type hint that could insert itself at some point (in my example at `...`, because then the whole hint would repeat itself) – 5t4cktr4c3 Jun 28 '21 at 17:51

1 Answers1

7

The yearned-for syntax is something like:

RecursiveDict = Dict[str, Union['RecursiveDict', int]]

As of now, MyPy (and most other Python type-checkers) don't support this syntax — the MyPy bug report asking for support for recursive types has been open for 6 years. However, some alternative type-checkers have recently introduced support for recursive annotations. So, it's a bit of a mixed bag.

See also:

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46