[issue42632] Reassgining ZeroDivisionError will lead to bug in Except clause

Dennis Sweeney report at bugs.python.org
Mon Dec 14 04:23:10 EST 2020


Dennis Sweeney <sweeney.dennis650 at gmail.com> added the comment:

This is just how local/nonlocal/global/builtin variables work in Python.

When you assign to a name anywhere inside of a function, all occurrences of that name refer by default to a local variable. So the line "ZeroDivisionError = 1" tells the foo() function that it has some local variable called "ZeroDivisionError". In order to make sure that the ZeroDivisionError always refers to the builtin exception, you need to add a global statement:

>>> def foo():
...     global ZeroDivisionError
...     try:
...         1/0
...     except ZeroDivisionError as e:
...         ZeroDivisionError = 1

>>> foo()
>>> ZeroDivisionError
1


See also: https://docs.python.org/3/faq/programming.html?highlight=global#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

----------
nosy: +Dennis Sweeney

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue42632>
_______________________________________


More information about the Python-bugs-list mailing list