1

This code snippet works:

try:
    raise Exception('oh no!')
except Exception as e:
    error = e

print(error) # prints "oh no!"

This code snippet fails:

try:
    raise Exception('oh no!')
except Exception as e:
    e = e

print(e) # NameError: name 'e' is not defined

What's going on?

actual_panda
  • 1,178
  • 9
  • 27
  • Related: https://stackoverflow.com/q/61318284/3001761. Python clears the target name, whatever's assigned to it. – jonrsharpe Aug 31 '21 at 10:34

1 Answers1

1

In Python,

except Exception as e:
    error = e

is equivalent to

except Exception as e:
    try:
        error = e
    finally:
        del e

I.e., e is deleted after the except block. If you assign e to e, it will be deleted - however, this is only true for the alias. If you assign it to error, e will also be deleted but not error.

Source: https://docs.python.org/3/reference/compound_stmts.html#the-try-statement

Leonard
  • 783
  • 3
  • 22
  • That's unexpected. It means I can't even do `e = 'hello'` in the `except` block like I would normally reassign names. – actual_panda Aug 31 '21 at 10:38
  • @actual_panda correct, and per the question I linked it'll clear stuff that was defined before the try, too. It shouldn't be unexpected, because this is how the try statement is documented. – jonrsharpe Aug 31 '21 at 10:39
  • @jonrsharpe ouch, that means you have to be very careful with the name you choose in the `... as ` part. I wonder if this couldn't be done better. – actual_panda Aug 31 '21 at 10:42