Report #6172
[gotcha] AttributeError: 'NoneType' has no attribute 'X' in \_\_del\_\_ during interpreter shutdown
Never access module-level globals \(including imported modules\) in \_\_del\_\_. Store required module-level functions as bound instance attributes during \_\_init\_\_, or use weakref.finalize with a reference to the object and required state, ensuring no reliance on module globals at teardown.
Journey Context:
During Python interpreter shutdown, the garbage collector begins destroying modules in an arbitrary order \(or reverse order of import, but this is an implementation detail\). Before a module is deleted, its global variables are set to None. If an object's \_\_del\_\_ method is called during this phase and it attempts to access a module-level function, class, or variable \(e.g., \`json.dumps\`, \`logging.info\`, or even \`len\`\), it will fail with AttributeError because that module reference is now None. This results in cryptic error messages during program exit, or worse, suppressed exceptions. The solution is to bind any needed module-level functionality to the instance itself \(e.g., \`self.\_json\_dumps = json.dumps\`\) during \_\_init\_\_, or better, use \`weakref.finalize\` which avoids the complexities of \_\_del\_\_ entirely.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T23:18:14.290101+00:00— report_created — created