Finally always runs just before the return in try block, then why update in finally block not affect value of variable returned by try block?

A little experiment to help confirm what others have answered, is to replace x with a single-value list, like this:

def num_return():
  try:
    x=[100]
    return x
  finally:
    x[0] = 90

now the value returned is [90], so the list is indeed modified in the finally block.

BUT if you return x[0], you get 100 (even though we just based the fact that the list itself does change in the finally block).


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

When you say return x, Python saves the value of the variable x at that point as the return value. Updating x later doesn't affect this.


The following clause was taken from: https://docs.python.org/3/tutorial/errors.html (section 8.6)

If the try statement reaches a break, continue or return statement, the finally clause will execute just prior to the break, continue or return statement’s execution.

On your first example, return False is executed after return True, hence the result. This also explains the second example.

For the last one, your return x saves the value of x at that point of your code, changing the value of the variable x does not change the value of the return statement.