I found the following behavior at least weird:
def errors():
try:
ErrorErrorError
finally:
return 10
print errors()
# prints: 10
# It should raise: NameError: name 'ErrorErrorError' is not defined
The exception disappears when you use return
inside a finally
clause. Is that a bug? Is that documented anywhere?
But the real question (and the answer I will mark as correct) is:
What is the python developers' reason to allow that odd behavior?
It is:
Here is an interesting comparison for return in finally block, among - Java/C#/Python/JavaScript: (archive link)
You asked about the Python developers' reasoning. I can't speak for them, but no other behavior makes sense. A function can either return a value, or it can raise an exception; it can't do both. The purpose of a "finally" clause is to provide cleanup code that is "guaranteed" to be run, regardless of exceptions. By putting a return statement in a finally clause, you have declared that you want to return a value, no matter what, regardless of exceptions. If Python behaved as you are asking and raised the exception, it would be breaking the contract of the "finally" clause (because it would fail to return the value you told it to return).
Returning from a finally is not a good idea. I know C# specifically forbids doing this.