Python变量命名/绑定混淆

Def*_*ult 9 python variables binding scope python-2.7

我对Python开发相对较新,在阅读语言文档时,我遇到了一行:

取消绑定封闭范围引用的名称是非法的; 编译器将报告一个SyntaxError.

因此,在学习练习中,我试图在交互式shell中创建此错误,但我无法找到这样做的方法.我使用的是Python v2.7.3,因此使用非本地关键字

def outer():
  a=5
  def inner():
     nonlocal a
     print(a)
     del a
Run Code Online (Sandbox Code Playgroud)

不是一个选项,并且不使用nonlocal,当Python del ainner函数中看到它时,它将它解释为一个尚未绑定的局部变量并抛出UnboundLocalError异常.

显然这个规则有一个关于全局变量的例外,那么我怎样才能创建一种情况,即我"非法"解除被封闭范围引用的变量名称的绑定?

Mar*_*ers 10

删除必须在外部范围内进行:

>>> def foo():
...     a = 5
...     def bar():
...         return a
...     del a
... 
SyntaxError: can not delete variable 'a' referenced in nested scope
Run Code Online (Sandbox Code Playgroud)

Python 3中删除了编译时限制:

$ 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 foo():
...     a = 5
...     def bar():
...         return a
...     del a
...     return bar
... 
>>>
Run Code Online (Sandbox Code Playgroud)

相反,NameError当您尝试引用时,会引发a a:

>>> foo()()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in bar
NameError: free variable 'a' referenced before assignment in enclosing scope
Run Code Online (Sandbox Code Playgroud)

我很想在这里提交文档错误.对于Python 2,文档具有误导性; 它正在删除触发编译时错误的嵌套作用域中使用的变量,并且Python 3中根本不再引发错误.


小智 5

要触发该错误,您需要在外部作用域的上下文中取消绑定变量.

>>> def outer():
...  a=5
...  del a
...  def inner():  
...   print a
... 
SyntaxError: can not delete variable 'a' referenced in nested scope
Run Code Online (Sandbox Code Playgroud)