Parse Python ImportError Stack Trace
Parse Python ImportError and ModuleNotFoundError tracebacks. Extract module paths, package names, and resolution chains to diagnose dependency and environment issues.
Detailed Explanation
Understanding Python ImportError Tracebacks
ImportError (and its subclass ModuleNotFoundError in Python 3.6+) is raised when Python cannot find or load a module. These errors are common during deployment, environment setup, and dependency management.
ImportError Traceback Example
Traceback (most recent call last):
File "/app/main.py", line 3, in <module>
from app.services.mailer import send_email
File "/app/services/mailer.py", line 1, in <module>
import boto3
ModuleNotFoundError: No module named 'boto3'
Common Causes
- Missing dependency --- package not installed in the current environment
- Virtual environment mismatch --- running code outside the venv where packages are installed
- Circular imports --- two modules importing each other, causing one to be partially loaded
- Name collision --- a local file has the same name as a standard library module
- Python version mismatch --- module only available in specific Python versions
- Path issues --- the module exists but is not on
sys.path
Diagnosis Steps
- Check the last line for the specific module name
- Verify the module is in your
requirements.txtorpyproject.toml - Run
pip listorpip show <module>to check if it is installed - Verify you are using the correct Python interpreter and virtual environment
- For circular imports, check the import chain in the traceback to identify the cycle
Environment-Specific Issues
Docker containers, serverless functions, and CI/CD pipelines often encounter ImportErrors because the build environment differs from the development environment. The traceback shows the exact import chain, which helps determine whether the issue is a missing package, wrong Python version, or path configuration problem.
Use Case
ImportErrors are among the first errors developers encounter when setting up a new project, deploying to a new environment, or upgrading dependencies. DevOps engineers debugging failed CI builds or crashed production containers need to quickly identify whether the issue is a missing package, version conflict, or environment misconfiguration. The traceback's import chain is the key diagnostic information.