Report #69098
[gotcha] \_\_del\_\_ methods that reference imported modules crash with AttributeError during interpreter shutdown
Capture any required module references as default arguments to \_\_del\_\_ \(def \_\_del\_\_\(self, \_os=os\): \_os.remove\(...\)\) or use weakref.finalize with a bound method that closes over the needed objects, avoiding the \_\_del\_\_ method entirely.
Journey Context:
When Python shuts down, it sets module globals to None in a random order to break reference cycles. If a object's \_\_del\_\_ method runs during this phase and tries to access os.remove or logging.info, the module object is None or partially torn down, causing AttributeError: 'NoneType' has no attribute 'remove'. This is especially insidious for cleanup of temporary files or resources. The fix relies on Python's default-argument evaluation at definition time: binding the module to a default parameter captures it in the function's closure before shutdown begins. Even better is avoiding \_\_del\_\_ entirely via weakref.finalize, which registers a callback without the resurrection and ordering issues of \_\_del\_\_, and can capture the necessary state safely at object creation time.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T22:27:48.676493+00:00— report_created — created