why this python program have the following output?

Question:

def makeInc (x, step):
    def next():
        nonlocal x, step
        x = x + step
        return x
    return next

x = makeInc (0, 1)
y = makeInc (0, 10)

x1=x()
x2=x()
y1=y()
y2=y()

print( x1, x2, y1, y2)

The output is 1 2 10 20.
I am not sure why it gives these outputs, can anyone explain it in detail? Thanks!

Asked By: loop

||

Answers:

The function makeInc() is a “factory” that makes function objects and returns them. The nonlocal declaration makes the function “close over” a variable. Usually you would make an explicit variable and close over that; in this case, the nonlocal declaration is closing over an argument variable from makeInc().

If you want to learn about closures and nonlocal here are a few references:

http://www.mondoinfo.com/blog/C182263547/E20060918200706/index.html

Python nonlocal statement

So, makeInc() makes a function object that has a start value and a “step” by which the start value will be incremented. Once you have made the custom function object, the final code calls the functions and gets the incrementing values.

Answered By: steveha