我一直在阅读标准线程库(
Python 2.6)中的一些代码,并且有一段代码让我感到奇怪.它可以缩短到以下结构(与threading.py中的__bootstrap_inner方法相比):
def foo(): exc_type,exc_value,exc_tb = sys.exc_info() try: # some code except: # some code finally: del exc_type,exc_tb
这些变量不会超出foo范围.有没有理由在最后删除这些引用?
解决方法
是的,至少对于exc_tb; traceback对象包含对当前帧的引用,这使得它成为循环引用.
通过删除本地引用,您可以打破该圈,因此您不必希望并相信垃圾收集器能够.
从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.