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

时间:2018-12-19 05:20:14

标签: python-3.x type-hinting

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

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

是否可以为arg指定类型提示,以表明它接受Iterable的{​​{1}}的任何级别?我怀疑不是,但是以为我会检查我是否缺少某些东西。

作为一种解决方法,我只是指定一些深度,然后以Garthok结尾。

Iterable[Any]

1 个答案:

答案 0 :(得分:3)

您可以使用type aliasesforward reference strings在键入语言中指定递归类型,

Garthoks = Union[Garthok, Iterable['Garthoks']]

但是mypy尚不支持递归类型,尽管最终可能会发生这种情况。