【问题标题】:Defining a recursive type hint in Python?在 Python 中定义递归类型提示?
【发布时间】:2019-05-19 13:53:50
【问题描述】:

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

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

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

【问题讨论】:

标签: python type-hinting python-typing


【解决方案1】:

您可以使用type aliases 和forward reference strings 指定打字语言中的递归类型,

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

请注意,mypy 尚不支持递归类型。 But it will likely be added eventually.


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


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

【讨论】:

  • 啊,明白了。谢谢! IDEA/PyCharm 似乎也不支持它。
  • @JesusFreke 我听说过其他一些 Python 类型检查器。除了mypy和pycharm,还有Facebook's Pyre和Google's pytype
  • 难道没有一种方法可以像typing 库中那样定义自己的自定义类型注释吗?我确信答案是肯定的,但我不知道怎么做。它只是一个声明所有 (Iterables of )*Garthoks 都是它的子类的类吗?
  • @DanielH 类是类型。您还可以使用 TypeVars 和子类 Generic 来实现 [] 语法。
  • 某些类型的前向引用由 PEP0563 处理。您可以通过 from __future__ import annotations 从 Python 3.7 开始使用它们
猜你喜欢
  • 2021-07-20
  • 1970-01-01
  • 2022-08-18
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多