Defining a recursive type hint in Python?
Solution 1:
You can specify recursive types in the typing language by using type aliases and forward reference strings,
Garthoks = Union[Garthok, Iterable['Garthoks']]
Note that recursive types are not yet supported by mypy. But it will likely be added eventually.
Update 2020/9/14: Microsoft announces support for recursive types in Pyright/Pylance.
Some types of forward references are handled by PEP0563. You can use them starting from Python 3.7 by doing from
__future__ import annotations
– Konstantin