ImportError: ‘Cannot import ‘mydb’ from module ‘connection’ – Solved

In this tutorial, we are going to discuss on how to solve the ImportError: ‘Cannot import ‘mydb’ from module ‘connection’ in Python with the help of example.

While programming in Python. a programmer can face many types of errors because of many kind of mistakes. But I am here to help you to solve the error mentioned in the title of this article.

You’re encountering an issue with your Python code, specifically the error message “ImportError: Cannot import ‘mydb’ from module ‘connection'”. This indicates a problem with how you’re importing a module. Let’s go through some steps to troubleshoot and fix the problem.

Confirm the Module Structure

Check that the mydb module is actually part of the connection module. Our project folders should be organized like you can see in the code below:

project/
├── connection/
│   ├── __init__.py
│   └── mydb.py
└── your_script.py

Validate Module Names

We have to ensure that module names match and are case-sensitive. If our module is named MyDB instead of mydb, adjust the import statement accordingly:

from connection import MyDB

Verify __init__.py

Make sure the connection directory is recognized as a package by having an __init__.py file inside. It can be empty, but it’s necessary.

Check PYTHONPATH

Confirm that the directory containing the connection package is in our Python path. If not, Python might not find the modules. In that case, we can modify sys.path or use relative imports:

import sys
sys.path.append('/path/to/project')

Watch for Circular Imports

Be cautious of circular imports, where mydb and connection import from each other. This can cause issues. Circular imports occur when two or more modules depend on each other, directly or indirectly, creating a loop in their dependencies.

Scrutinize for Typos

Review your import statement and file names for typos. Python is case-sensitive, so ensure everything is spelled correctly.

I hope, taking these steps is going to help you to fix the issue.

Leave a Comment

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

Scroll to Top