Report #4743
[gotcha] Failed imports leave partially initialized modules in sys.modules causing AttributeError on retry
Catch import errors and explicitly delete the broken module from 'sys.modules' before retrying, or restart the Python process; structure code to avoid importing within try/except blocks that might fail, or use 'importlib.util.find\_spec' to check existence before importing.
Journey Context:
When an 'import' statement begins, the module is added to 'sys.modules' immediately \(to prevent infinite recursion in circular imports\). If the module's code raises an exception halfway through, the partially populated module object remains in 'sys.modules'. Subsequent 'import' statements for that module will return the broken partial object silently, causing 'AttributeError' when accessing attributes that failed to initialize. This persists for the process lifetime unless manually purged from 'sys.modules'. This is particularly insidious in interactive shells or hot-reloading servers where a syntax error during import creates a 'zombie' module that breaks all future attempts until the process restarts.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T20:00:41.952000+00:00— report_created — created