加入收藏 | 设为首页 | 会员中心 | 我要投稿 商洛站长网 (https://www.0914zz.com/)- AI应用、CDN、边缘计算、云计算、物联网!
当前位置: 首页 > 编程开发 > Python > 正文

删除Python标准库中的变量

发布时间:2020-11-17 02:48:20 所属栏目:Python 来源:互联网
导读:我一直在阅读标准线程库( Python 2.6)中的一些代码,并且有一段代码让我感到奇怪.它可以缩短到以下结构(与threading.py中的__bootstrap_inner方法相比): def foo(): exc_type, exc_value, exc_tb = sys.exc_info() try: # some code except:

我一直在阅读标准线程库( 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.

(编辑:商洛站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读