def foo(): exc_type,exc_value,exc_tb = sys.exc_info() try: # some code except: # some code finally: del exc_type,exc_tb
这些变量不会超出foo范围.有没有理由在最后删除这些引用?
解决方法
通过删除本地引用,您可以打破该圈,因此您不必希望并相信垃圾收集器能够.
从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.