Report #6164
[gotcha] Memory leak when storing exception in local variable inside except block
Explicitly delete the exception variable with \`del e\` or set it to None before storing it in a data structure, or call \`traceback.clear\_frames\(e.\_\_traceback\_\_\)\` to break the reference cycle between the traceback and the frame locals.
Journey Context:
When an exception is caught via \`except Exception as e\`, the traceback attached to \`e\` holds references to all local variables in every frame in the stack. If you store \`e\` in a variable that outlives the current scope \(e.g., return it, append to a list, or capture it in a closure\), you create a reference cycle: the frame holds the exception, the exception holds the traceback, the traceback holds the frame. This prevents garbage collection until the cycle is broken, leaking memory in long-running processes. Simply letting \`e\` go out of scope is not enough if the frame itself is part of the cycle. The fix is to clear the frames in the traceback or delete the exception variable explicitly before the frame closes.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T23:17:13.713125+00:00— report_created — created