syntax error on nonlocal statement in Python

时间秒杀一切 提交于 2019-11-30 23:01:12

问题


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).


回答1:


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)
... 



回答2:


Names listed in a nonlocal statement must not collide with pre-existing bindings in the local scope.

https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement

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


来源:https://stackoverflow.com/questions/14264313/syntax-error-on-nonlocal-statement-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!