Diagnose stale pycache import mismatch
Use when Python reports an error like:
ImportError: cannot import name 'X' from 'module'- but the referenced source file already contains
X
Why this matters
This failure is often misdiagnosed as a missing code change. In practice, common causes are:
- stale
.pycbytecode in__pycache__/ - the wrong virtualenv/interpreter
- a long-lived process still using old imports
- multiple copies of the repo/module on disk
Procedure
Confirm the symbol exists in the live source file.
- Read the exact file path shown in the traceback.
- Verify the function/class really exists there now.
Confirm where Python is importing from.
- Activate the intended environment.
- Run a tiny import script and print
module.__file__. - Check
hasattr(module, 'symbol').
Check both common local environments if the repo has more than one.
- In hermes-agent, both
venvand.venvmay exist. - Validate imports under each when the failing process is unclear.
- In hermes-agent, both
If source is correct but import still fails, clear local bytecode.
- Target the module cache first:
rm -f __pycache__/module*.pyc - If needed, clear repo caches:
find . -path '*/__pycache__/*' -delete
- Target the module cache first:
Re-run the minimal import check.
- Example:
python - <<'PY'import moduleprint(module.__file__)print(hasattr(module, 'symbol'))PY
- Example:
Re-run targeted regression tests around the affected import path.
- Prefer the smallest relevant set first, then widen if needed.
Hermes-agent-specific pattern
In /home/vamsee/.hermes/hermes-agent, when a traceback references utils.py but a newly added helper is already present in that file:
- Read
utils.pyand confirm the helper exists. - Import it under both environments if both exist:
source venv/bin/activatesource .venv/bin/activate
- Print
utils.__file__and verifyhasattr(utils, 'helper_name'). - Remove local cached bytecode:
rm -f __pycache__/utils.cpython-311.pyc __pycache__/utils.cpython-313.pyc
- Re-run the import and targeted pytest selection.
Good verification bundle
source venv/bin/activate
python - <<'PY'
import utils
print(utils.__file__)
print(hasattr(utils, 'base_url_host_matches'))
PY
find . -path '*/__pycache__/*' -delete
pytest -q tests/test_base_url_hostname.py
Decision rule
- If
module.__file__points somewhere unexpected: fix environment/path selection. - If
module.__file__is correct and symbol is missing only before cache clear: stale bytecode was the likely cause. - If imports succeed in a fresh shell but fail in the original process: restart that long-lived process/session.
Pitfalls
- Do not assume the traceback path means the running interpreter has reloaded that file.
- Do not stop after reading source; always verify with a live import.
- Do not clear only site-packages caches if the failing module is from the repo root.
- If both
venvand.venvexist, checking only one can hide the real problem.