Circular Imports in Python
**packages : directory with __init__.py
**modules : files with .py extension
**submodules : modules that are inside larger package and subset of term module
Circular Imports: When 2 files are imported modules from each other.
When the import is used in Python files to import modules, that import will be dynamically executed and the modules will be generated on demand as required.
While having circular imports, the issue arises when the import of the first module gets called, another module is supposed to be created but another module also depends on the creation of the first module. This is where deadlock occurs.
The basic solution would be to stop the dynamic initiation of modules on the invocation of Python modules.
How to resolve the issue :
def func():
from package import b
In b.py
def func():
from package import a
2. Errors using imported objects with circular dependencies :
Now, while you may be able to import a module with a circular import dependency, you won't be able to import any objects defined in the module or actually be able to reference that imported module anywhere in the top level of the module where you're importing it. You can, however, use the imported module inside functions and code blocks that don't get run on import.
For example, this will work:
package/a.py
import package.b
def func_a():
return "a"
package/b.py
import package.a
def func_b():
# Notice how package.a is only referenced *inside* a function
# and not the top level of the module.
return package.a.func_a() + "b"