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
).
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.
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.
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.
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).
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)
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With