Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type hints for variably-nested Dict in Python [duplicate]

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?


1 Answers

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:

  • Defining a recursive type hint in Python?

  • Recursive type annotations

like image 165
Alex Waygood Avatar answered May 27 '26 07:05

Alex Waygood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!