If I try the following code, I see that the normal block return value is not returned, but the finally block return value is:
>>> def f():
... try:
... return "normal"
... finally:
... return "finally"
...
>>> f()
'finally'
A more advanced example is to call a function in each return statement:
In that situation, I can see that:
- In the normal block, the
show
function is evaluated (but not return), - In the finally block, the
show
function is evaluated and returned:
>>> def show(x):
... print(x)
... return x
...
>>> def g():
... try:
... return show("normal")
... finally:
... return show("finally")
...
>>> g()
normal
finally
'finally'
Is it a good practice the have a return statement in a finally clause? Or, is it a potential error (which should be detected by a code analysis tools or a code review)?
EDIT
Another example with an exception:
>>> def f():
... try:
... raise ValueError("bad")
... finally:
... return "good"
...
>>> f()
'good'
Weird!