Report #96662
[bug\_fix] ImportError: cannot import name 'X' from 'Y' \(stale \_\_pycache\_\_ after git pull\)
Delete all \`\_\_pycache\_\_\` directories and \`.pyc\` bytecode files: \`find . -type d -name "\_\_pycache\_\_" -exec rm -rf \{\} \+ 2>/dev/null \|\| true\`. Alternatively, run Python with the \`-B\` flag \(\`python -B script.py\`\) to ignore bytecode, or set the environment variable \`PYTHONDONTWRITEBYTECODE=1\` to prevent creation of stale cache files during development. The root cause is that Python's import system checks timestamps on \`.pyc\` files against \`.py\` files, but if a module was deleted or moved, a stale \`.pyc\` in \`\_\_pycache\_\_\` may shadow a new module or create a ghost module with old attributes.
Journey Context:
A developer is working on a feature branch where \`utils/helpers.py\` contains a function \`format\_date\(\)\`. They switch to the main branch via \`git pull origin main\`, where that file was refactored: \`utils/\` is now a namespace package and \`format\_date\` moved to \`utils/time/format.py\`. They run their test suite and get \`ImportError: cannot import name 'format\_date' from 'utils.helpers'\`. They check the source code: \`utils/helpers.py\` no longer exists in the editor, and the import statement in the test file looks correct \(pointing to the new location\). They check \`sys.path\` and PYTHONPATH, which are correct. They eventually run \`python -c "import utils.helpers; print\(utils.helpers.\_\_file\_\_\)"\` and discover it points to a \`.pyc\` file deep inside \`utils/\_\_pycache\_\_/\` that contains the ghost of the old module. The \`\_\_pycache\_\_/helpers.cpython-311.pyc\` file survived the \`git checkout\` because git doesn't track compiled files, and Python's import system found and loaded the stale bytecode before realizing the source \`.py\` was gone, creating a partially initialized module that confused the import machinery.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T20:49:53.598686+00:00— report_created — created