Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Finally' statement executes twice in a recursive function [Python 3.6]p

I tried googling it but couldn't find a similar problem. I am sure it's something silly but I can't seem to get it.

I have the following code:

def f(a):
    try:
        4 / a
    except:
        f(2)
    else:
        print('else')
    finally:
        print("finally")

When I call the function with 0 as the argument: f(0)
It returns:

else
finally
finally

So in my understanding here is what should happen:

  • 0 gets fed to the function;
  • try statement can't execute it;
  • except statement gets triggers, which calls the function again with a legal argument, 2.
  • try statement is now okay;
  • else statement prints else
  • finally statement prints finally

Why does finally gets printed twice?

like image 334
4247 Avatar asked Jun 15 '26 17:06

4247


1 Answers

When you invoke with f(0), the finally block is called twice. Once for the call to f(2) and then again for the enclosing call to f(0).

This is because 4 / 0 leads to an exception, which triggers the second call to f via f(2).

finally will be invoked first for the call to f(2), then for the call to f(0) - because f(2) is invoked from f(0).

like image 169
Owen Avatar answered Jun 17 '26 05:06

Owen