0

I'm confused by the behavior of python's nonlocal keyword.

So the standard example is as in this question: there is a def outerfoo(): block containing a variable definition outvar = 0, and inside outerfoo() there is a def innerfoo(): block containing nonlocal outvar, making it so that the value of outvar in outerfoo():'s namespace can be changed by what goes on inside innerfoo().

So far so good. However, the following code fails with a SyntaxError:

outvar = 0 #not in any function
def foo():
    nonlocal outvar
    outvar += 1
foo()

What namespace is the parser looking in, that it is not finding outvar?

Community
  • 1
  • 1
MSmedberg
  • 381
  • 3
  • 13
  • 1
    `nonlocals` are used inside functions that are inside functions, in your example you should use `global outvar`. – Ashwini Chaudhary Mar 23 '13 at 17:35
  • I know that `global outvar` will work. My question, which was not answered in [Python nonlocal statement](http://stackoverflow.com/questions/1261875/python-nonlocal-statement), is why a variable binding in the top-level or main scope is not recognized as the intended binding for a `nonlocal` statement in a top-level `def` block. Similarly, [PEP 3104](http://www.python.org/dev/peps/pep-3104/) does not specify that `nonlocal` only works in functions defined inside other functions. – MSmedberg Mar 24 '13 at 17:29

0 Answers0