17.11.20 11:55, Mark Shannon пише: > I'm wondering why > ``` > x = "value" > try: > 1/0 > except Exception as x: > pass > ``` > > does not restore "value" to x after > the `except` block. > > There doesn't seem to be an explanation for this behavior in the docs or > PEPs, that I can find. > Nor does there seem to be any good technical reason for doing it this way.
Others already said that it is because "except" does not create a new scope. But why it does not create a new scope? Because it is a design of Python. In general, since in Python local variables do not have declarations, inner scopes do not work. For example: y = 1 if x: y = 2 If "if" create a new scope, "y" after "if" would be restored to 1. But what if make an exception for "except" and make a special rule for it? First, "Special cases aren't special enough to break the rules". Second, how would you use it? This feature would only encourage to write hard-to-read and errorprone code. This error is so common, that in some other programming languages which support inner scopes shadowing local variable causes compiler warning or even syntax error. So this feature is a misfeature. There is also historical reason. In Python 2 the variable was not deleted after leaving the except block. Now it is deleted, and if the code uses the variable after this it would raise a NameError. It is a clear indication of program error. With your proposition it would have some other value, and program error would not be caught so easily. _______________________________________________ Python-Dev mailing list -- python-dev@python.org To unsubscribe send an email to python-dev-le...@python.org https://mail.python.org/mailman3/lists/python-dev.python.org/ Message archived at https://mail.python.org/archives/list/python-dev@python.org/message/LMMNJLNWGCWVMDSFFZHSPYT4RFIEO3ZR/ Code of Conduct: http://python.org/psf/codeofconduct/