Python Circular Imports
What is a Circular Dependecy ?
When two or more modules rely on each other, this is referred to as a circular dependency. This is due to the fact that each module is defined in terms of the others.
Python cyclic imports
Let's take these two python files as an example
# file1
import file2
def printName(): print("OWC")
printName()
# file2
import file1
def printAddress(): print("Kigali")
printAddress()
Once that's done, let's try running file1.py, It worked like a charm right.
The output:
OWC
Kigali
OWC
The above output seems legit, however, let's make a small change to our code.
Let's import the functions particularly instead of the whole file.
# file1
from file2 import printAddress
def printName():
print("OWC")
printName()
printAddress()
# file2
from file1 import printName
def printAddress():
print("Kigali")
printAddress()
printName()
When we try to run `python3 file1.py` we get this error in our terminal
``` Traceback (most recent call last): File "file1.py", line 1, in <module> from file2 import printAddress File "/Users/bruce/workspace/journals/file2.py", line 1, in <module> from file1 import printName File "/Users/bruce/workspace/journals/file1.py", line 1, in <module> from file2 import printAddress ImportError: cannot import name 'printAddress' from partially initialized module 'file2' (most likely due to a circular import) (/Users/bruce/workspace/journals/file2.py) ```
Python is showing us an ```ImportError ``` and that it is most likely due to a circular import
To avoid circular import errors, you can move ```from module import X``` to a place it is needed.
For example
# file1
def printName():
print("OWC")
printName()
from file2 import printAddress
printAddress()
# file2
def printAddress():
print("Kigali")
printAddress()
from file1 import printName
printName()
Wrapping up
Circular imports are a specific case of circular references. In general, they can be solved through better code design. However, the resulting design may contain a large amount of code or may combine unrelated functionalities (tight coupling)