This question already has an answer here:
There is the interesting code below:
def func1():
try:
return 1
finally:
return 2
def func2():
try:
raise ValueError()
except:
return 1
finally:
return 3
func1()
func2()
Could please somebody explain, what results will return these two functions and explain WHY, i.e. describe the order of the execution
From the Python documentation
So once the try/except block is left using return, which would set the return value to given - finally blocks will always execute, and should be used to free resources etc. while using there another return - overwrites the original one.
In your particular case,
func1()
return2
andfunc2()
return3
, as these are values returned in the finally blocks.It will always go to the
finally
block, so it will ignore thereturn
in thetry
andexcept
. If you would have areturn
above thetry
andexcept
, it would return that value.Putting
print
statements beforehand really, really helps:This returns:
You'll notice that python always returns the last thing to be returned, regardless that the code "reached"
return 1
in both functions.A
finally
block is always run, so the last thing to be returned in the function is whatever is returned in the finally block. Infunc1
, that's 2. Infunc2
, that's 3.func1()
returns 2.func2()
returns 3.finally
block is executed finally regardless or exception.You can see order of execution using debugger. For example, see a screencast.