Reputation: 1
I’m working on a large Python project, and I’ve come across a situation where two or more modules have circular dependencies. For example, module A imports module B, and module B imports module A (directly or indirectly). This is causing an ImportError because the interpreter can’t resolve the dependencies. I have the following structure: Module A
from module_b import func_b
def func_a():
print("This is function A")
func_b()
Module B
from module_a import func_a
def func_b():
print("This is function B")
func_a()
When I try to run the code, I get the error:
ImportError: cannot import name 'func_a' from partially initialized module 'module_a'
My Questions related to this?
Upvotes: 0
Views: 41
Reputation: 98
# module_a.py
def func_a():
from module_b import func_b # Import moved inside the function
print("This is function A")
func_b()
# module_b.py
def func_b():
from module_a import func_a # Import moved inside the function
print("This is function B")
func_a()
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from module_b import func_b
Upvotes: 0