Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
814 views
in Technique[技术] by (71.8m points)

Defining a recursive type hint in Python?

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]]]]]]]]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...