Search code examples
pythonpython-3.xcpythonpython-execpython-nonlocal

Using nonlocal inside exec


Why does the following code:

exec("""
a = 3
def b():
  nonlocal a
  a = a + 1
b() #error occurs even without this call
print(a)
"""
)

)

give this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 4
SyntaxError: no binding for nonlocal 'a' found

This is some more text to satisfy the text/code ratio.


Solution

  • The nonlocal statement looks for the variable you name in an enclosing function namespace (and raises an error if there is no such variable in any such namespace). If there is no enclosing function, you don't want nonlocal. If you want a variable at the top level, you want to use the global statement instead.