[FIX] ImportError: ‘Cannot import ‘mydb’ from module ‘connection’

Handling Import Errors In Python Due To Circular Imports

Making mistakes is how we learn, whether we’re playing a game, doing homework, or writing code on a computer. In Python, a computer language, there are many kinds of mistakes we can make, which we call errors. Consider this guide your map, helping you find and fix the ImportError. So, if you’ve made a mistake in Python and aren’t sure how to fix it, don’t worry – this article is here to help!

Exploring Various Error Types in Python

There are three main types of errors in python. They are:

  • Syntax Errors – These errors occur when there is something wrong in the grammar of the code. In simpler words, if the Python interpreter is unable to read the code due to typos or mistakes in the code such as wrong indentation level(IndentationError is a type of syntax error in python) . It stops the program from running because your interpreter cannot understand what your code is trying to say.
  • Logical errors – These errors might not raise an actual error in the code of a program but they will give you a wrong output for the correct input. For example, if you want to calculate the factorial of a number, but you make a mistake in the formula, then you will definitely receive an output but it won’t be the one you desired.
  • Runtime Errors – These are the most common errors in Python that occur. Most of the errors that are raised come under this type. Errors such as ImportError, AttributeError, etc are all part of runtime errors. Runtime errors stops the normal flow of a program because there is something that’s stopping its execution. During runtime, if the interpreter is unable to carry out some actions, it raises a runtime error.

For example, the Error: importerror – cannot import name ‘mydb’ from partially initialized module ‘connection’ in Python, is caused due to a circular import when the name of your script or any other module included in your script has the same name as the built-in module “connection” or if the functions inside that module has the same name as any other python file in your specified directory.

Demystifying ImportError: Causes and Solutions

The word “import” generally means to bring something from abroad to one’s own country. In Python, imports are a type of function call which includes other modules in one single python script. For example, if you write import module_name in the beginning of a program, it signals the interpreter to include that particular module in your code and allows you to use the functions defined inside the other module.

Import errors are caused by a number of reasons. Such as:

  • The imported module is not installed and could not be found or if the module doesn’t exist.
  • The imported module is not in the correct directory or there is a problem with the PATH of the file.
  • ImportError can also be raised due to a syntax error when the module name is incorrectly spelled.
  • The most common reason is circular imports. Circular dependency or circular import refers to the problem caused when one module is called from inside another module and it goes in an infinite loop leading to system crashes and recursion. For example, the error: importerror – cannot import name ‘mydb’ from partially initialized module ‘connection’ in Python, is caused due to a circular import, and in this article, we will look at how to solve it. To know more in-depth about circular dependencies, check out this article!
Causes Of ImportError
Unraveling the Causes of ImportError

This is how an ImportError looks like:

ImportError: cannot import name 'mydb' from partially initialized module 'connection' 
(most likely due to a circular import)
 (C:\Users\Shreya\Python 3.11\scripts\connection.py)

Similar: Python Attribute Error – (Solved).

Exception Handling: A Tool for ImportError Resolution

Import errors are caused due to circular imports, most of the time.

The most common solution is to check for any other Python files that might have the same name as your working script or any other files in your directory or PATH. Changing the name of your Python file is the easiest method to solve this problem. For example, in the previous section, the error is caused because our file name is “connection.py” which is the same as the name of the module “connection”.

So, if you change your file name all your problems will disappear. Circular imports is one of the reasons why it is always advised to not name your scripts the same as modules or keywords.

Inside your code, you can also solve this problem using exception handling. Exception handling is the method of handling errors and warnings in Python. It makes use of the try and except clauses to format the output so that the error message is displayed in a more structured and coherent manner.

The try and except clause is very easy to use. First, the code under the try clause is executed, and if the interpreter runs into any error during this process, then the except clause is executed interrupting the normal flow of the program, else the try block completes its run and the flow of the program is smooth without any interruptions.

Mastering the ‘Try’ and ‘Except’ Clauses for Error Handling

This is how you can use the try and except clause to handle import error caused due to circular imports and then display the message, “Change the name of your file or check for files that have the same name.” or something similar.

#using try clause
    #trying to import the same module from the second section
    from connection import mydb
except ImportError :
    #handling the error using except
    print("Change the name of your file to something else or check if other files exist with the same name as the imported module.")

Also read: Python Exception Handling – Try, Except, Finally

Error Handling: Final Thoughts on ImportError

This article revolves around errors in Python, especially ImportError. We have taken a look at what causes ImportErrors and why they might be a hassle. But, on the other hand, these errors are one of the easiest to solve. Even without using exception handling, you can easily get rid of ImportErrors by changing the name of your Python scripts accordingly. Most of the time circular imports cause this error but other times there might be different reasons. What other errors do you often come across while coding in python?