Except-clause removes a local variable

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

# ...

print(exc)

NameError: name 'exc' not defined

This is used to work in Python2. Why has this changed so much? If I could at least reassign exc, similar to class level attributes

class Foo(object):
    Bar = Bar

but this does not make it work:

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

Any good tips to achieve the same? I would rather not write something like this:

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

# ...

print(exc)
+4
source share
1 answer

The operator tryexplicitly limits the scope of the associated exception to prevent circular references causing leakage. See Documentation try:

, , except.

[...]

, , except. , , , .

; , - .

Python 2 , .

Python 2 , . sys.exc_info():

. traceback , , . -, , . , - exctype, value = sys.exc_info()[:2] . , ( try ... finally) exc_info() , .

, :

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

Source: https://habr.com/ru/post/1544981/


All Articles