跨模块转发引用

Forward references across modules

在Python类型中,循环依赖可以通过前向引用来解决:

class A:
    b: "B"

    def __init__(self, b: "B"):
        self.b = b


class B:
    a: A

    def __init__(self):
        self.a = A(self)

mypy 将成功进行类型检查。

但是,如果我将 AB 分开 files/modules:

a.py:

class A:
    b: "B"

    def __init__(self, b: "B"):
        self.b = b

b.py:

from .a import A


class B:
    a: A

    def __init__(self):
        self.a = A(self)

并使用 mypy 检查模块或包,它失败了:

$ mypy -p tt
tt/a.py:2: error: Name 'B' is not defined
tt/a.py:4: error: Name 'B' is not defined

除了将两者放在同一个文件中之外,还有其他解决方法吗?

(使用 Python 3.8.4 测试)

编辑:

对于循环导入的讨论,我添加了一个琐碎的__main__.py

from .b import B

B()

并用 python -m tt

进行测试

因为我最近 你可以使用 TYPE_CHECKING 变量:

# a.py
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from .b import B


class A:
    b: "B"

    def __init__(self, b: "B"):
        self.b = b
# b.py
from .a import A


class B:
    a: A

    def __init__(self):
        self.a = A(self)