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?
When
alpha(1, gamma)is called,alpha(2, beta)is called sincenumis equal to1. Here, it passes a reference to thebetafunction currently defined inside this invocation of thealphafunction which holds a closure over the values of the parameters. Thus thisbetafunction sees the value ofnumas the value before the next invocation ofalpha, so1is printed later. If you also addprint(proc)insidebeta, you'll see thatprocis equal to thegammafunction which was first passed toalpha.