It simply clears the local reference to self
, making sure that if an exception occurs the reference passed to self._loop.call_exception_handler()
is the only remaining reference and no cycle has been created.
This is still needed here because the local namespace is referenced by the exception traceback; it will not be cleared up when the function exits as there is a reference to the locals alive still.
This is documented in the sys.exc_info()
function documentation with a warning:
Warning: Assigning the traceback return value to a local variable in a function that is handling an exception will cause a circular reference. This will prevent anything referenced by a local variable in the same function or by the traceback from being garbage collected. Since most functions don’t need access to the traceback, the best solution is to use something like
exctype, value = sys.exc_info()[:2]
to extract only the exception type and value. If you do need the traceback, make sure to delete it after use (best done with atry ... finally
statement) or to callexc_info()
in a function that does not itself handle an exception.
Because tulip
handlers form a fundamental framework class the code handles the traceback circular reference case by removing self
from the local namespace instead, as it cannot guarantee that the _callback
or call_exception_handler
functions will clear up their references.
In CPython, objects are destroyed when their reference count drops to 0, but a cyclic reference (a series of objects referencing themselves in a cycle) will never see their reference count drop to 0. The garbage collector does try to break such cycles but it cannot always do this or not fast enough. Explicitly clearing references avoids creating cycles.
For example, if there is a __del__
method, the garbage collector will not break a cycle as it won't know in what order to break a cycle safely in that case.
Even if there is no __del__
method (which a framework class should never assume will not be the case) it's best to not rely on the garbage collector eventually clearing cycles.