OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Defining a recursive type hint in Python?

  • Thread starter Thread starter JesusFreke
  • Start date Start date
J

JesusFreke

Guest
Let's say I have a function that accepts a Garthok, an Iterable[Garthok], an Iterable[Iterable[Garthok]], etc.

Code:
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].

Code:
Union[Garthok,
    Iterable[Union[Garthok,
        Iterable[Union[Garthok, 
            Iterable[Union[Garthok, Iterable[Any]]]]]]]]
<p>Let's say I have a function that accepts a <code>Garthok</code>, an <code>Iterable[Garthok]</code>, an <code>Iterable[Iterable[Garthok]]</code>, etc.</p>

<pre><code>def narfle_the_garthoks(arg):
if isinstance(arg, Iterable):
for value in arg:
narfle_the_garthoks(arg)
else:
arg.narfle()
</code></pre>

<p>Is there any way to specify a type hint for arg that indicates that it accepts any level of <code>Iterable</code>s of <code>Garthok</code>s? I suspect not, but thought I'd check if I'm missing something.</p>

<p>As a workaround, I'm just specifying a few levels deep, and then ending with <code>Iterable[Any]</code>.</p>

<pre><code>Union[Garthok,
Iterable[Union[Garthok,
Iterable[Union[Garthok,
Iterable[Union[Garthok, Iterable[Any]]]]]]]]
</code></pre>
 
Top