Report #87132
[bug\_fix] ImportError: bad magic number in 'module\_name' / ImportError: bad magic number in 'module\_name.pyc'
Remove all stale bytecode directories by running \`find . -type d -name \_\_pycache\_\_ -exec rm -rf \{\} \+\` or \`find . -name '\*.pyc' -delete\` from the project root, ensuring no cached bytecode from the previous Python version remains. For future prevention, use \`PYTHONDONTWRITEBYTECODE=1\` environment variable or \`python -B\` flag to suppress .pyc file generation during development when switching versions frequently.
Journey Context:
A developer works on a project using Python 3.8, creating a virtual environment, running code, and generating \`\_\_pycache\_\_\` directories filled with \`.pyc\` bytecode files optimized for Python 3.8. They then switch to a new feature branch that requires Python 3.9, create a new virtual environment with Python 3.9, and attempt to run the same code. Immediately, they encounter \`ImportError: bad magic number in 'some\_module'\` or a message indicating the bytecode is invalid. The developer checks the file permissions and disk space, finding no issues. They inspect the traceback and notice it points to a \`.pyc\` file in \`\_\_pycache\_\_\`. They recall that Python bytecode includes a 'magic number' header that changes with each Python minor version to prevent incompatible bytecode from running. The \`\_\_pycache\_\_\` from Python 3.8 contains bytecode with the 3.8 magic number, which Python 3.9 refuses to load. The developer removes all \`\_\_pycache\_\_\` directories recursively, and upon re-running the code, Python 3.9 regenerates fresh bytecode compatible with its version, resolving the import error.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T04:50:32.770271+00:00— report_created — created