在 Python 中定义递归类型提示? [英] Defining a recursive type hint in Python?
问题描述
假设我有一个接受 Garthok
、Iterable[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 指定一个类型提示,表明它接受 Garthok
s 的任何级别的 Iterable
s?我怀疑没有,但我想我会检查我是否遗漏了什么.
Is there any way to specify a type hint for arg that indicates that it accepts any level of Iterable
s of Garthok
s? 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屋!