Removing Variables in Python Standard Libraries

I read some of the code in the standard thread library (Python 2.6), and there was a piece of code that made me think. It can be shortened to the following structure (compared to the __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 beyond the scope of foo . Is there any reason to remove these links at the end?

+6
source share
1 answer

Yes, at least for exc_tb ; trace objects contain a link to the current frame, and this makes it a round link.

By deleting the local link, you break this circle, so you do not need to hope and trust that the garbage collector can.

From sys.exc_info() of the docs functions :

Warning Assigning the traceback return value to a local variable in the function that handles the exception will cause a circular reference. This will prevent anything referenced by a local variable in the same function, or tracing from garbage collection. Since most functions do not require access to the trace, the best solution is to use something like exctype, value = sys.exc_info()[:2] to extract only the type and value of the exception. If you need a trace, be sure to delete it after use (best done using the try ... finally try ) or call exc_info() in a function that does not handle the exception.

+8
source

All Articles