except-clause 删除局部变量

2024-04-20Python开发问题
3

本文介绍了except-clause 删除局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

# ...

print(exc)

NameError: name 'exc' is not defined

This used to work in Python2. Why was it changed this way? If I could at least re-assign to exc, similar to class-level attributes

class Foo(object):
    Bar = Bar

but this does not make it work either:

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

Any good hints to achieve the same? I'd prefer not to write something like this:

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

# ...

print(exc)

解决方案

The try statement explictily limits the scope of the bound exception, to prevent circular references causing it to leak. See the 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.

Emphasis mine; note that your only option is to bind the exception to a new name.

In Python 2, exceptions did not have a reference to the traceback, which is why this was changed.

However, even in Python 2, you are explicitly warned about cleaning up tracebacks, see 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.

If you do re-bind the exception, you may want to clear the traceback explicitly:

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

这篇关于except-clause 删除局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11