Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

syntax error on nonlocal statement in Python

I would like to test the example of the use of the nonlocal statement specified in the answer on this question:

def outer():
   x = 1
   def inner():
       nonlocal x
       x = 2
       print("inner:", x)
   inner()
   print("outer:", x)

but when I try to load this code, I always get a syntax error:

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
  File "t.py", line 4
    nonlocal x
             ^
SyntaxError: invalid syntax

Does anybody know what I am doing wrong here (I get the syntax error for every example that I use, containing nonlocal).

like image 378
JasperTack Avatar asked Jan 10 '13 18:01

JasperTack


People also ask

What does nonlocal mean in Python?

The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function. Use the keyword nonlocal to declare that the variable is not local.

Is nonlocal good practice Python?

Yep this is a good summary. Very good point about thread safety, and not one I had considered, thanks for that. The return option is one I initially considered before favouring the "cleaner" non-local approach. That being said, it's much more versatile and probably something to consider as a general practice.

What is syntactical error in Python?

Syntax errors are produced by Python when it is translating the source code into byte code. They usually indicate that there is something wrong with the syntax of the program. Example: Omitting the colon at the end of a def statement yields the somewhat redundant message SyntaxError: invalid syntax.

What does no binding for nonlocal mean?

How nonlocal works. If you use nonlocal , that means that Python will, at the start of the function, look for a variable with the same name from one scope above (and beyond).


1 Answers

nonlocal only works in Python 3; it is a new addition to the language.

In Python 2 it'll raise a syntax error; python sees nonlocal as part of an expression instead of a statement.

This specific example works just fine when you actually use the correct Python version:

$ python3.3
Python 3.3.0 (default, Sep 29 2012, 08:16:08) 
[GCC 4.2.1 Compatible Apple Clang 3.1 (tags/Apple/clang-318.0.58)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def outer():
...    x = 1
...    def inner():
...        nonlocal x
...        x = 2
...        print("inner:", x)
...    inner()
...    print("outer:", x)
... 
like image 163
Martijn Pieters Avatar answered Sep 24 '22 05:09

Martijn Pieters