Let's say I have a function that accepts a Garthok
, an Iterable[Garthok]
, an Iterable[Iterable[Garthok]]
, etc.
def narfle_the_garthoks(arg): if isinstance(arg, Iterable): for value in arg: narfle_the_garthoks(arg) else: arg.narfle()
Is there any way to specify a type hint for arg that indicates that it accepts any level of Iterable
s of Garthok
s? I suspect not, but thought I'd check if I'm missing something.
As a workaround, I'm just specifying a few levels deep, and then ending with Iterable[Any]
.
Union[Garthok, Iterable[Union[Garthok, Iterable[Union[Garthok, Iterable[Union[Garthok, Iterable[Any]]]]]]]]
Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.
Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.
Python's type hints provide you with optional static typing to leverage the best of both static and dynamic typing. Besides the str type, you can use other built-in types such as int , float , bool , and bytes for type hintings. To check the syntax for type hints, you need to use a static type checker tool.
The term Recursion can be defined as the process of defining something in terms of itself. In simple words, it is a process in which a function calls itself directly or indirectly. Advantages of using recursion. A complicated function can be split down into smaller sub-problems utilizing recursion.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With