为什么非本地不创建新的外部变量(与全局不同)

Why does nonlocal not create new outer variable (unlike global)

我在阅读 Python 3 教程时注意到 globalnonlocal 关键字之间的区别 here

如果我尝试以下代码,它会起作用:

# Does not need: spam = ''
def global_scope_test():
  def do_global():
    global spam
    spam = 'global spam'

  do_global()

global_scope_test()
print(spam)

而以下不是:

def nonlocal_scope_test():
  # Needs: spam = ''
  def do_nonlocal():
    nonlocal spam
    spam = 'nonlocal spam'

  do_nonlocal()
  print(spam)

nonlocal_scope_test()

为什么 global 允许在全局范围内创建新绑定,而 nonlocal 不允许在外部范围内创建新绑定?鉴于这两个功能的相似性,这似乎是一个奇怪的怪癖。该教程似乎没有突出显示示例中的差异,我也找不到任何线程讨论它。

documentation for nonlocal说清楚了:

Names listed in a nonlocal statement, unlike those listed in a global statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).