0
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!

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
loop
  • 219
  • 2
  • 5
  • 12
  • Throws syntax errors. – Hariprasad Dec 20 '13 at 06:41
  • @Hariprasad it worked correctly for me. I'm using Python 3.3.1, which version are you using? – steveha Dec 20 '13 at 07:25
  • Does this answer your question? [Python nonlocal statement / keyword](https://stackoverflow.com/questions/1261875/python-nonlocal-statement-keyword) and [What do lambda function closures capture?](https://stackoverflow.com/questions/2295290/) – Karl Knechtel Sep 11 '22 at 07:40

1 Answers1

0

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.

Community
  • 1
  • 1
steveha
  • 74,789
  • 21
  • 92
  • 117