Here's what's happening in this function:
- Line 1 creates
test()
, which is a closure factory function. This means that it creates a new closure each time it’s called and then returns the closure to the caller.
- Line 2 defines
add()
, which is an inner function that takes a single argument, base, and returns the result of the expression a*b
.
- Line 6 returns
add()
as a function object, without calling it.
The question now is where does add()
get the value of a
from? This is where the closure comes into play. add()
gets the value of a
from the outer function, test()
. Here’s what Python does when you call test()
in line 9:
- Define a new instance of
add()
, which takes a single argument base.
- Take a snapshot of the surrounding state of
add()
, which includes
a
with its current value (in line 9 you are defining it as a = 4
).
- Return
add()
along with its whole surrounding state.
This way, when you call the instance of add()
returned by test()
in line 10, you’ll see that the function remembers the value of a
! So what you have is the previously assigned value of a = 4
(line 9), and the newly passed argument - the value of b = 4
(line 10).
Hope this helps to clarify!