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

Jes*_*eke 4 type-hinting python-3.x

假设我有一个接受a Garthok,an Iterable[Garthok],an Iterable[Iterable[Garthok]]等的函数。

def narfle_the_garthoks(arg):
  if isinstance(arg, Iterable):
    for value in arg:
       narfle(arg)
  else:
    arg.narfle()
Run Code Online (Sandbox Code Playgroud)

有什么方法可以为arg指定类型提示,以指示它接受Iterables中Garthoks的任何级别?我怀疑不是,但以为我会检查我是否缺少某些东西。

解决方法是,我仅指定几个级别,然后以结尾Iterable[Any]

Union[Garthok,
    Iterable[Union[Garthok,
        Iterable[Union[Garthok, 
            Iterable[Union[Garthok, Iterable[Any]]]]]]]]
Run Code Online (Sandbox Code Playgroud)

gil*_*lch 7

您可以使用类型别名正向引用字符串,在键入语言中指定递归类型,

Garthoks = Union[Garthok, Iterable['Garthoks']]
Run Code Online (Sandbox Code Playgroud)

请注意,mypy尚不支持递归类型。但最终可能会添加。

  • 某些类型的前向引用由 PEP0563 处理。从 Python 3.7 开始,您可以通过执行“from __future__ import comments”来使用它们 (2认同)
  • 不幸的是,不可能写成 `NestedList = list[str | "NestedList"]` 而不是 `NestedList = list[Union[str, "NestedList"]]` 因为它会引发 `TypeError: |: 'type' 和 'str'` 不受支持的操作数类型。 (2认同)