>def f(x): > try: > quot = 10 / x > except ZeroDivisionError as exc: > log_error(exc) > return 0 > else: > log_return(quot) > return quot + 1 > finally: > "Any cleanup processing needed before returning"
This involves defining the new variable quot, which is only defined, when the try block succeeds. quot is undefined in the except block and in the finally block after an exception occured. The scoping of that variable is fragile and it is hard to track, why that variable is declared and where it is used. This also worsens the readability of the coding and worsens the expandability, for example, if you want to do something in the finally block later. >def f(x): > try: > quot = 10 / x > except ZeroDivisionError as exc: > log_error(exc) > res = 0 > else: > log_return(quot) > res = quot + 1 > finally: > return res This is even worse. The variable res is declared in both branches. If you want to catch another exception different from ZeroDivisionError, you would have to declare res again, because the finally block is always run and now expects this variable. A finally block depending on variables declared in the except or else block is very confusing. __exit_context__ would solve this issue, because that magic variable would be always available and you don't have to juggle with local variables. The finally block can write to the return value, so there is no reason to hide the return value or already caught exceptions here. This would make the code much cleaner and avoids messing up with the scope of variables. -- https://mail.python.org/mailman3//lists/python-list.python.org