Finally block runs just before the return statement in the try block, as shown in the below example - returns False
instead of True
:
>>> def bool_return():
... try:
... return True
... finally:
... return False
...
>>> bool_return()
False
Similarly, the following code returns value set in the Finally block:
>>> def num_return():
... try:
... x=100
... return x
... finally:
... x=90
... return x
...
>>> num_return()
90
However, for variable assignment without return statement in the finally block, why does value of variable updated by the finally block not get returned by the try block? Is the variable from finally block scoped locally in the finally block? Or is the return value from the try block held in memory buffer and unaffected by assignment in finally block? In the below example, why is the output 100 instead of 90?
>>> def num_return():
... try:
... x=100
... return x
... finally:
... x=90
...
>>> num_return()
100
Similarly the following example:
In [1]: def num_return():
...: try:
...: x=[100]
...: return x
...: finally:
...: x[0] = 90
...:
In [2]: num_return()
Out[2]: [90]
In [3]: def num_return():
...: try:
...: x=[100]
...: return x[0]
...: finally:
...: x[0] = 90
...:
In [4]: num_return()
Out[4]: 100