在 Python 中定义递归类型提示? [英] Defining a recursive type hint in Python?

查看:66
本文介绍了在 Python 中定义递归类型提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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()

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

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.

作为一种解决方法,我只是指定了几个深度,然后以 Iterable[Any] 结尾.

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]]]]]]]]

推荐答案

您可以使用 类型别名前向引用字符串,

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

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

Note that recursive types are not yet supported by mypy. But it will likely be added eventually.

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

Update 2020/9/14: Microsoft announces support for recursive types in Pyright/Pylance.

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

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

这篇关于在 Python 中定义递归类型提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆