This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: except statement turns defined variable into undefined
Type: behavior Stage:
Components: Interpreter Core Versions: Python 3.2, Python 3.3, Python 3.4
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: brett.cannon, mark.dickinson, serhiy.storchaka
Priority: normal Keywords:

Created on 2012-12-17 19:38 by serhiy.storchaka, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (4)
msg177657 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2012-12-17 19:38
Example:

>>> err = None
>>> try: raise ValueError
... except ValueError as err: pass
... 
>>> err
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'err' is not defined

It is expected that either the variable will have the catched value, or save the old value, or the compiler will raise an error. But it didn't even warns.
msg177660 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2012-12-17 19:47
This is a deliberate feature of Python 3.  See PEP 3110.
msg177662 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2012-12-17 20:03
I understand that such behavior change needed was a good reason. But the current behavior is quite confusing.
msg177689 - (view) Author: Brett Cannon (brett.cannon) * (Python committer) Date: 2012-12-18 13:40
As Mark pointed out, this is on purpose and is not going to change since Python lacks block-level scoping of variables and thus causes the last case related to the variable to take precedence. It might be a little unexpected, but it's not that unreasonable when you think about scoping rules and understand how 'except' blocks work.
History
Date User Action Args
2022-04-11 14:57:39adminsetgithub: 60907
2012-12-18 13:40:15brett.cannonsetstatus: open -> closed

nosy: + brett.cannon
messages: + msg177689

resolution: rejected
2012-12-17 20:03:27serhiy.storchakasetmessages: + msg177662
2012-12-17 19:47:52mark.dickinsonsetnosy: + mark.dickinson
messages: + msg177660
2012-12-17 19:38:45serhiy.storchakacreate