在 Python 中定义递归类型提示?

Defining a recursive type hint in Python?

假设我有一个接受 GarthokIterable[Garthok]Iterable[Iterable[Garthok]] 等的函数

def narfle_the_garthoks(arg):
  if isinstance(arg, Iterable):
    for value in arg:
       narfle_the_garthoks(arg)
  else:
    arg.narfle()

有什么方法可以为 arg 指定一个类型提示,表明它接受 IterableGarthok 的任何级别?我怀疑没有,但我想我会检查一下我是否遗漏了什么。

作为解决方法,我只是指定了几个深度级别,然后以 Iterable[Any] 结束。

Union[Garthok,
    Iterable[Union[Garthok,
        Iterable[Union[Garthok, 
            Iterable[Union[Garthok, Iterable[Any]]]]]]]]

您可以使用 type aliases and forward reference strings

在打字语言中指定递归类型
Garthoks = Union[Garthok, Iterable['Garthoks']]

请注意,mypy 尚不支持递归类型。 But it will likely be added eventually.


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