How to Fix ModuleNotFoundError in Python
In this tutorial, you'll learn about How to Fix ModuleNotFoundError in Python. We cover key concepts, practical examples, and best practices.
Python raises ModuleNotFoundError when an import statement refers to a module that does not exist in the current Python environment's search path.
The Wrong Way
import pandas as pd
df = pd.DataFrame({"A": [1, 2, 3]})
print(df)
This produces:
Traceback (most recent call last):
File "script.py", line 1, in <module>
import pandas as pd
ModuleNotFoundError: No module named 'pandas'
The Right Way
Install the module and verify the import:
pip install pandas
import pandas as pd
df = pd.DataFrame({"A": [1, 2, 3]})
print(df)
Output:
A
0 1
1 2
2 3
Step-by-Step Fix
1. Verify Python and pip versions match
python3 --version
pip3 --version
# Ensure both point to the same Python installation
If they mismatch, use:
python3 -m pip install pandas
2. Activate the correct virtual environment
# Check if a venv exists
ls venv/
# Activate it
source venv/bin/activate
# Verify the environment
which python
3. Check for local module shadowing
If you named your script pandas.py, it shadows the real pandas import:
# Wrong -- script named pandas.py
# import pandas # imports your script, not the library
# Rename your file
mv pandas.py my_pandas_script.py
4. Install from requirements.txt
python3 -m pip install -r requirements.txt
5. Check sys.path for the search locations
import sys
for path in sys.path:
print(path)
Prevention Tips
- Create a
requirements.txtfile for every project. - Use virtual environments to isolate dependencies.
- Name your scripts differently from library names.
- Run
pip listto verify installations. - Use
python3 -m pip installto avoid pip-version mismatches.
Common Mistakes with modulenotfound
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
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