删除Python标准库中的变量

前端之家收集整理的这篇文章主要介绍了删除Python标准库中的变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在阅读标准线程库( 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 a tryfinally statement) or to call exc_info() in a function that does not itself handle an exception.

猜你在找的Python相关文章