Is it an error to return a value in a finally clause
IMHO, having a return
in a finally
clause is bad practice if there is a return
statement in the related try
or except
blocks.
try:
# lots of spaghetti code
return fancy_expression_with_side_effects
except AllKindsOfError:
# lots of alternative spaghetti code
finally:
# many a mouse wheel spin down the module
# lots of clean up
return eternal_return_value
While this would constitute valid Python, it really should't. The first return
statement will partially execute: you will observe the side effects of evaluating fancy_expression_with_side_effects
(try return print('foo')
there) and it will still not return that expression's value. I have once scratched my head for a couple of hours in that exact situation.
If, however, the return statement in the finally
is the only return statement, one will be able to easily follow the step-by-step execution flow in a simple expected manner and I don't see too much fault in it, but would stilll be very careful:
In many software projects, you might be the senior Python guy who knows such stuff, but what guarantee do you have that no one else will add a return
statement elsewhere later on?