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?
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 atry
...finally
statement) or to callexc_info()
in a function that does not itself handle an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With