Deleting variables in Python standard libraries

I’ve been reading some of the code in a standard threading library ( Python 2.6 ) and there was a piece of code which made me wonder. It can be shorten to the following structure ( compare to __bootstrap_inner method in ):

def foo():
    exc_type, exc_value, exc_tb = sys.exc_info()
        # some code
        # some code
        del exc_type, exc_value, exc_tb

These variables do not go outside of foo scope. Is there any reason to delete these references at the end?

Best answer

Yes, at the very least for exc_tb; traceback objects hold a reference to the current frame, and that makes this a circular reference.

By deleting the local reference you break that circle, so you don’t have to hope and trust that the garbage collector will be able to.

From the sys.exc_info() function docs:

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 a tryfinally statement) or to call exc_info() in a function that does not itself handle an exception.