python2.7 在函数中删除一个全局变量不报SyntaxError?
大家讲道理
大家讲道理 2017-04-17 11:05:10
0
2
311
a = 3

def x():
  global a
  del(a)

print(a)
x()

在python2.7中执行上面这段代码并没有问题!但是在python2.7的文档中(没有锚记,大概在第10段)
有这样一句话:
It is illegal to unbind a name referenced by an enclosing scope; the compiler will report a SyntaxError.
我在SO上也看到了同样的一个提问,但是它答案给出的测试代码是这样的:

>>> def outer():
...     a=5
...     def inner():
...         nonlocal a
...         print(a)
...         del a
SyntaxError: can not delete variable 'a' referenced in nested scope

但是在python2.7中,并没有nonlocal这个关键字(事实上,我在3.2上测试上面这段代码也是没有问题的)。我想知道,如果这文档(2.7)上这句话是正确的,那么测试代码(2.7)是怎样的?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
小葫芦

is correct. "an enclosing scope" refers to "within the closure", not "within the function". For functions within a closure, the reference to upvalue (the variable in the upper layer) is immutable.

伊谢尔伦

Look here http://stackoverflow.com/questions/29...

local is not enclosing scope

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template