Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward references across modules [duplicate]

In Python typing, circular dependencies can be resolved with a forward reference:

class A:
    b: "B"

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


class B:
    a: A

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

mypy will typecheck that successfully.

Howerver, if I split A and B in separate 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)

And use mypy to check either the modules or the package, it fails:

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

Is there a way to resolve that other than by putting both in the same file?

(Tested with Python 3.8.4)

Edit:

For the discussion of circular imports, I added a trivial __main__.py:

from .b import B

B()

And test with python -m tt

like image 901
Zulan Avatar asked Mar 28 '26 09:03

Zulan


1 Answers

As I recently suggested you can use TYPE_CHECKING variable:

# 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)
like image 186
alex_noname Avatar answered Mar 29 '26 23:03

alex_noname



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!