gpt4 book ai didi

python - except 子句删除局部变量

转载 作者:太空狗 更新时间:2023-10-30 00:55:49 33 4
gpt4 key购买 nike

exc = None
try:
raise Exception
except Exception as exc:
pass

# ...

print(exc)

NameError: name 'exc' is not defined

这曾经在 Python2 中工作。为什么会变成这样?如果我至少可以重新分配给 exc,类似于类级属性

class Foo(object):
Bar = Bar

但这也不能使它工作:

exc = None
try:
raise Exception
except Exception as exc:
exc = exc

有什么好的提示可以实现相同的目标吗?我不想写这样的东西:

exc = None
try:
raise Exception("foo")
except Exception as e:
exc = e

# ...

print(exc)

最佳答案

try 语句显式 限制了绑定(bind)异常的范围,以防止循环引用导致其泄漏。查看try statement documentation :

When an exception has been assigned using as target, it is cleared at the end of the except clause.

[...]

This means the exception must be assigned to a different name to be able to refer to it after the except clause. Exceptions are cleared because with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs.

强调我的;请注意,您唯一的选择是将异常绑定(bind)到新名称。

在 Python 2 中,异常没有对回溯的引用,这就是它被更改的原因。

但是,即使在 Python 2 中,也会明确警告您清理回溯,请参阅 sys.exc_info() :

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 try ... finally statement) or to call exc_info() in a function that does not itself handle an exception.

如果你确实重新绑定(bind)了异常,你可能想要明确地清除回溯:

try:
raise Exception("foo")
except Exception as e:
exc = e
exc.__traceback__ = None

关于python - except 子句删除局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24271752/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com