The Circular Imports in Python programming occur when two or more modules mutually depend on each at the same time forming a loop between them. These modules' dependency on each other often results in the program getting stuck and generating circular import errors.
What does the Python Circular Error Mean?
Sometimes there may occur a situation when, let us say a person, A needs a person B to do some work. But simultaneously person B needs person A to do some work. This causes both A and B to depend on each other. A similar situation occurs in programming while importing modules and is known as Circular imports. In this article, we will learn more about circular imports and what problems they may cause.
Analyze Circular Imports in Python
Let us see a simple example to know how this error occurs.
Example: Here we will create two modules, 'mod1' and 'mod2' that contains a function 'display1' and 'display2', respectively to print some data. We will import 'mod1' into 'mod2' and vice-versa so that they depend on each other simultaneously and use their functions accordingly.
mod1.py
Python
# import module2
import mod2
def display1():
print("I am display1 from module 1")
# using mod2's function display2
mod2.display2()
mod2.py
Python
# importing module 1
import mod1
def display2():
print("I am display2 of module 2")
# calling mod1's function display1
mod1.display1()
Output:
Python Circular Import
Fix Python Circular Import Error
Now that we are familiar with how the circular import occurs in Python, we will see how we can avoid and fix this issue.
- Import modules when needed
- Use Python importlib library
- Create a Module for shared code
Import the Module when needed
One simple way to fix circular imports is to import a module when it is needed. We usually import a module at the beginning of the code, but this time to avoid circular import issue, we import the module inside a function where it is required to do the job.
Example: Unlike previous example, this time we will import the module just before we require its function in another module.
mod1.py
Python
def display1():
print("I am display1 from module 1")
# import module when needed
import mod2
mod2.display2()
mod2.py
Python
def display2():
print("I am display2 of module 2")
# import module when needed
import mod1
mod1.display1()
Output:
When mod1.py is executed
I am display2 of module 2
I am display1 from module 1
I am display2 of module 2
Use Python importlib module
Python's importlib module is used to dynamically import modules during runtime in the program. Here to avoid circular imports we have used importlib module's import_module() function.
Example: In this example, instead of simple python module import statement we are importing modules using the import_module() function and providing the module to be imported as the parameter.
mod1.py
Python
# import importlib module
import importlib
def display1():
print("I am display1 from module 1")
# import mod2 using importlib.import_module()
module = importlib.import_module("mod2")
module.display2()
mod2.py
Python
# import importlib module
import importlib
def display2():
print("I am display2 of module 2")
# import mod1 using importlib.import_module()
module = importlib.import_module("mod1")
module.display1()
Output:
I am display2 of module 2
I am display1 from module 1
I am display2 of module 2
Create a Module for shared code
Another way to avoid circular imports is by creating a new module. This module will contain all the content that is shared among different modules which was the main reason for dependency. Now the modules can easily refer to this new module without causing circular import issue.
Example: In this example we will create an extra module 'common.py' that will contain the shared functionalities of the previous two modules.
common.py
Python
def display3():
print("I am display 3 from common.py")
mod1.py
Python
# import common module
import common
def display1():
print("I am display1 from module 1")
common.display3()
display1()
mod2.py
Python
# import common module
import common
def display2():
print("I am display2 from module 2")
common.display3()
display2()
Output:
On executing the mod1.py, we will get the following output.
I am display1 from module 1
I am display 3 from common.py
Similar Reads
__import__() function in Python
__import__() is a built-in function in Python that is used to dynamically import modules. It allows us to import a module using a string name instead of the regular "import" statement. It's useful in cases where the name of the needed module is know to us in the runtime only, then to import those mo
2 min read
Python - Import module outside directory
Modules are simply a python .py file from which we can use functions, classes, variables in another file. To use these things in another file we need to first import that module into that file. If the module exists in the same directory as the file, we can directly import it using the syntax import
4 min read
Python - Import from parent directory
In this article, we will learn how to Import a module from the parent directory. From Python 3.3, referencing or importing a module in the parent directory is not allowed, From the below example you can clearly understand this. In the parent directory, we have a subdirectory, geeks.py file and in th
5 min read
Create and Import modules in Python
In Python, a module is a self-contained Python file that contains Python statements and definitions, like a file named GFG.py, can be considered as a module named GFG which can be imported with the help of import statement. However, one might get confused about the difference between modules and pac
3 min read
Libraries in Python
Normally, a library is a collection of books or is a room or place where many books are stored to be used later. Similarly, in the programming world, a library is a collection of precompiled codes that can be used later on in a program for some specific well-defined operations. Other than pre-compil
8 min read
Python Crash Course
If you are aware of programming languages and ready to unlock the power of Python, enter the world of programming with this free Python crash course. This crash course on Python is designed for beginners to master Python's fundamentals in record time! Experienced Python developers developed this fre
7 min read
Python - Import from sibling directory
In this article, we will discuss ways to import files from the sibling directory in Python. First, create two folders in a root folder, and in each folder create a python file. Below is the dictionary tree: Directory Tree: root : | |__SiblingA: | \__A.py | |__SiblingB: | \__B.py In B.py we will crea
3 min read
Lazy import in Python
In this article, we will learn how to do Lazy import in Python. For this, let's first understand the lazy import. What is Lazy Import? It is a feature of the Pyforest module that allows the user to perform the task without adding libraries to the code snippet as the task of this function is to add t
5 min read
Python Fire Module
Python Fire is a library to create CLI applications. It can automatically generate command line Interfaces from any object in python. It is not limited to this, it is a good tool for debugging and development purposes. With the help of Fire, you can turn existing code into CLI. In this article, we w
3 min read
Conda vs Poetry in Python
When it comes to managing Python environments and dependencies, two tools often stand out: Conda and Poetry. Each has its strengths and specific use cases, catering to different needs within the Python development community. This article explores the key features, advantages, and differences between
4 min read