为什么`global`语句不影响当前块内的块?

时间:2019-06-13 11:42:39

标签: python scoping

        serializer = HeroCounterSerializer(instance, data=request.data, partial=True)

尝试运行包含以上所列代码的模块将导致def foo(): global a def bar(): nonlocal a a = 6 bar() a = 5 foo() print(a) 。但是我希望它可以运行并打印SyntaxError: no binding for nonlocal 'a' found,为什么不呢?

请注意,如果我们将6语句替换为绑定名称global a的语句(例如afrom something import otherthing as a),则没有{{1} },然后a = 0语句按预期输出SyntaxError

我读了https://docs.python.org/3/reference/executionmodel.html#naming-and-binding,但不理解print(a)5的语句。

2 个答案:

答案 0 :(得分:1)

a绑定在顶级名称空间中。

  

nonlocal语句使对应的名称引用最近的封闭函数范围中的先前绑定的变量。

但是a没有绑定在函数范围内,所以

  

SyntaxError在编译时引发

换句话说,global不会影响a的绑定位置。

答案 1 :(得分:-2)

a = 5
def foo():
    global a
    def bar():
        global a
        a = 6
    bar()
foo()
print(a)

此打印6

nonlocal语句使对应的名称引用最近的封闭函数范围中的先前绑定的变量。