Circular imports can drive you mad in Python. Here’s one I’m too stupid to solve.
I have a base class with lots of functionality, that needs to emit itself, and also all kinds of its sub-classes:
# base.py
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from a import A
from b import B
class BaseClass:
def foo(self) -> A:
pass
def bar(self) -> B:
pass
def baz(self) -> BaseClass:
pass
And there are the several sub-classes, which in comparison are relative lightweight and there are many more of them:
# a.py
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from base import BaseClass
from b import B
class A(BaseClass):
def foo(self) -> B:
pass
def bar(self) -> BaseClass:
pass
and another one:
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from base import BaseClass
from a import A
class B(BaseClass):
def foo(self) -> A:
pass
def bar(self) -> BaseClass:
pass
However I try to run this, it will fai due to circular imports.
from a import A
from b import B
my_a:A = A()
my_b:B = my_a.foo()
Anyone any Idea how to solve this puzzle. The problem is that all classes needs to deal with the base class and 0…N sub-classes. Type hints/annotations are a must, as the code is part of an open-source library.
As of toady I have all code in just one file, but that’s a mess with 2500 lines of code. Many thanks in advance.