如何定义递归 Iterable 类型?

How to define a recursive Iterable type?

我正在尝试定义递归 Iterable 类型 Iterable_of_TOIs:

# from __future__ import annotations
from typing import overload, Optional, Iterable, Union


class ToI:
    """
    ToI = Token or Iterable of ToIs
    """
    Iterable_of_ToIs = Iterable[Union[ToI, 'Iterable_of_ToIs']]

    @overload
    def __init__(self, *, token: str) -> None:
        ...

    @overload
    def __init__(self, *, iterable: Iterable_of_ToIs) -> None:
        ...

    # actual implementation
    def __init__(
            self,
            token: Optional[str] = None,
            iterable: Optional[Iterable_of_ToIs] = None
    ) -> None:
        self.token: Optional[str] = token
        self.iterable: Optional[Iterable_of_ToIs] = iterable

但是 mypy 抱怨

我做错了什么?

看来,我做错的并不多。

关于 error: Name 'Iterable_of_ToIs' is not defined:
PEP 613动机 部分(状态 Accepted)我发现:

Type aliases are declared as top level variable assignments.

哎呀!在任何其他文档中找不到 Python 3.9 或更早版本的此规则,尤其是在 PEP 484.

中找不到

但无论如何...它解释了错误。那么,好吧,让我们把这条线移到顶层。

关于error: Cannot resolve name "Iterable_of_ToIs" (possible cyclic definition)
似乎还不支持:https://github.com/python/mypy/issues/731