繁体   English   中英

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

[英]Defining a recursive type hint in Python?

假设我有一个 function 接受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 指定一个类型提示,表明它接受Garthok的任何级别的Iterable 我怀疑不是,但我想我会检查我是否遗漏了什么。

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

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

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

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

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


2020/9/14 更新: Microsoft 宣布支持 Pyright/Pylance 中的递归类型。


某些类型的前向引用由PEP0563处理。 你可以从 Python 3.7 开始使用它们,方法是 from __future__ import annotations – Konstantin

MyPy 有这个限制,它还不支持循环引用,但我找到了一种使用 TypeVars 的方法,如下所示:

from typing import TypeVar, TypeAlias, Iterable, Union

T = TypeVar('T')
_Garthoks: TypeAlias = Union[T, Iterable[T]]
Garthoks: TypeAlias = _Garthoks[_Garthoks[_Garthoks[_Garthoks]]]
# you can nest it as deep as you need...

目前,我发现它是 MyPy 支持此功能的最佳解决方案。

我希望它能解决你的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM