Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a recursive type hint in Python?

Tags:

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 Iterables of Garthoks? 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]]]]]]]] 
like image 350
JesusFreke Avatar asked Dec 19 '18 05:12

JesusFreke


People also ask

How do you define a recursion in Python?

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.

How do you type hint in Python?

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.

Does Python have type hints?

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.

What is recursion in Python explain with an example?

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.


1 Answers

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

like image 121
gilch Avatar answered Sep 16 '22 21:09

gilch