Diagnosing Import Errors
Common Import Error Types
Python developers frequently encounter several types of import errors:
graph TD
A[Import Errors] --> B[ModuleNotFoundError]
A --> C[ImportError]
A --> D[SyntaxError]
A --> E[AttributeError]
ModuleNotFoundError
This error occurs when Python cannot locate the specified module:
## Example of ModuleNotFoundError
import non_existent_module
## Typical error message
## ModuleNotFoundError: No module named 'non_existent_module'
ImportError
Happens when a module exists but cannot be imported correctly:
## Example of ImportError
from math import non_existent_function
## Typical error message
## ImportError: cannot import name 'non_existent_function'
Diagnostic Strategies
Error Analysis Techniques
Error Type |
Diagnostic Steps |
Possible Solutions |
ModuleNotFoundError |
Check module installation |
Use pip to install |
ImportError |
Verify module path |
Check import syntax |
SyntaxError |
Review import statement |
Correct syntax mistakes |
Python Debugging Commands
## Check Python path
python3 -c "import sys; print(sys.path)"
## List installed packages
pip list
## Install missing module
pip install module_name
Advanced Diagnostics
Sys Module Inspection
import sys
## Print module search paths
print(sys.path)
## Check loaded modules
print(sys.modules)
Common Troubleshooting Scenarios
- Missing Third-Party Modules
## Install missing module
sudo pip3 install numpy
- Virtual Environment Issues
## Create virtual environment
python3 -m venv myenv
## Activate virtual environment
source myenv/bin/activate
LabEx Recommendation
When encountering import errors, LabEx suggests systematically checking:
- Module installation
- Python path configuration
- Virtual environment setup
Error Resolution Workflow
graph TD
A[Import Error Detected] --> B{Module Exists?}
B -->|No| C[Install Module]
B -->|Yes| D{Path Correct?}
D -->|No| E[Adjust Python Path]
D -->|Yes| F[Check Import Syntax]
Best Practices
- Always use virtual environments
- Keep track of installed packages
- Use consistent Python versions
- Regularly update packages