Search code examples
pythonfunctionclosuresnested-function

Program output with nested function and function parameter


Given the following code

def alpha(num, proc):

    def beta(): print(num)

    if num == 1:
        alpha(2, beta)
    else:
        proc()

def gamma():
    pass

alpha(1, gamma)

I expected the output to be 2, since my logic was:

   alpha(1, gamma)
=> alpha(2, beta)  # since num == 1
=> proc()          # since num != 1
=> beta()
=> print(2)        # since beta was a parameter alongside 2

However, the actual output is code is 1. Could anyone please explain why this is the case?


Solution

  • When alpha(1, gamma) is called, alpha(2, beta) is called since num is equal to 1. Here, it passes a reference to the beta function currently defined inside this invocation of the alpha function which holds a closure over the values of the parameters. Thus this beta function sees the value of num as the value before the next invocation of alpha, so 1 is printed later. If you also add print(proc) inside beta, you'll see that proc is equal to the gamma function which was first passed to alpha.