How to Fix ImportError: No module named 'X' in Python
In this tutorial, you'll learn about How to Fix ImportError: No module named 'X' in Python. We cover key concepts, practical examples, and best practices.
Python raises ImportError: No module named 'X' when an import statement cannot find the requested module in the current Python environment.
The Wrong Way
import requests
response = requests.get("https://api.example.com")
This produces:
Traceback (most recent call last):
File "script.py", line 1, in <module>
import requests
ImportError: No module named 'requests'
The Right Way
Install the missing module before importing:
pip install requests
import requests
response = requests.get("https://api.example.com")
print(response.status_code)
Output:
200
Step-by-Step Fix
1. Install the missing module
pip install module_name
If you have multiple Python versions, use the correct pip:
python3 -m pip install module_name
2. Check your virtual environment
# Activate your virtual environment
source venv/bin/activate
# Verify the module is installed
pip list | grep module_name
3. Verify the module name
The import name may differ from the package name:
pip install python-dateutil
import dateutil # import name may be different
Check the package documentation for the correct import statement.
4. Check for circular imports in your own code
# file_a.py
from file_b import func_b
def func_a():
pass
# file_b.py
from file_a import func_a # circular import
def func_b():
pass
Restructure to avoid circular dependencies:
# file_a.py
def func_a():
pass
# file_b.py
import file_a
def func_b():
file_a.func_a()
Prevention Tips
- Always use a virtual environment for each project.
- Use
pip freeze > requirements.txtto track dependencies. - Run
python3 -m pip install -r requirements.txtin new environments. - Use import names from official documentation, not package names.
- Check
sys.pathif imports fail in unusual project layouts.
Common Mistakes with importerror
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro