It does state this in the doc, but it’s not at all obvious just glancing - you’d expect the
return True to be successful, and thus the
finally return statement not to execute because a return statement had already executed (as opposed to the finally releasing resources or printing to the console).
An aside - I believe this example is non-obvious from the docs. I suppose one could infer that “before leaving the try statement” means before a return statement in the try executes, but I would find this non-obvious. I’d expect it to be like code after a
yield statement, the yield yields something, then the code after it runs, except if the code in the finally is a return, it doesn’t run because the function has already returned.
>>> print('first statement')
>>> print('last executed statement')
last executed statement
I believe the docs could be made clearer, specifying that the
finally executes before a return statement in a
try, as I on first read interpret “on the way out” as meaning after rather than before completing the final statement in flow changing/breaking cases’.
I’ve submitted a PR https://github.com/python/cpython/pull/15677 - if anyone has better wording than mine, feel free