1

I am trying to use nonlocal keyword in python in the following code. inner() is enclosed in outer() and I want to create a counter variable that will remember how many times inner() is called from outer(). ctr is defined in outer() and as nonlocal in inner().

But I am getting error as no binding for nonlocal 'ctr' found.

def inner1():
    nonlocal ctr
    ctr=ctr+1
    print(' ctr= {0}'.format(ctr))


def outer1():
    ctr=0
    for i in range(5):
        inner1()

outer1()
bner341
  • 525
  • 1
  • 7
  • 8
  • 1
    `inner()` being called within `outer` is not equivalent to `inner` defined inside `outer`. nonlocal works with the latter. – Ashwini Chaudhary Aug 27 '17 at 17:43
  • 1
    *Names listed in a nonlocal statement, unlike those listed in a global statement, must refer to pre-existing bindings in an enclosing scope*... Where is that variable defined in the enclosing scope?? – OneCricketeer Aug 27 '17 at 17:45

1 Answers1

2

inner() is enclosed in outer()

No, inner is not enclosed in outer (not defined within the scope of outer), you're only calling inner from outer; there isn't any closure here.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139