Avoiding Circular Import Errors in Python: 3 Effective Strategies | by Yanick Andrade

SeniorTechInfo
1 Min Read

Understanding How Python Import Statements Work

Circular import issues in Python can be a pain, especially if you are a beginner. Today, I was working on a new internal library that we use in multiple places to speed up the coding process, and I ran into this issue.
It’s a good idea to show you three ways that you can avoid or minimize the risk of running into this same issue. Like always, I will start from the beginning by giving a brief introduction to what circular import is in Python and why it constitutes a problem.
— Circular Import in Python
Circular import is a common problem that can happen in Python when we have two or more modules depending on each other.
# Example of circular import
api.py -> settings.py -> database.py -> settings.py 
In the example above, we can see four modules that mutually depend on each other— api.py imports settings.py, which database.py, which imports settings.py.
When this happens you will get an ImportError message at runtime or execution time — depending on how you are importing.
In this article, we are going to cover:

  • How Python import statement works
Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *