Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 threading.py ):

def foo():
    exc_type, exc_value, exc_tb = sys.exc_info()
    try:
        # some code
    except:
        # some code
    finally:
        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?

like image 576
freakish Avatar asked Feb 14 '13 09:02

freakish


1 Answers

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

like image 71
Martijn Pieters Avatar answered Sep 24 '22 23:09

Martijn Pieters