Why doesn't Python's nonlocal keyword like the global scope?

前端 未结 4 1297
一生所求
一生所求 2021-02-01 21:08

In Python 3.3.1, this works:

i = 76

def A():
    global i
    i += 10

print(i) # 76
A()
print(i) # 86

This also works:

def en         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-01 21:14

    why is a module's scope considered global and not an enclosing one? It's still not global to other modules (well, unless you do from module import *), is it?

    If you put some name into module's namespace; it is visible in any module that uses module i.e., it is global for the whole Python process.

    In general, your application should use as few mutable globals as possible. See Why globals are bad?:

    • Non-locality
    • No Access Control or Constraint Checking
    • Implicit coupling
    • Concurrency issues
    • Namespace pollution
    • Testing and Confinement

    Therefore It would be bad if nonlocal allowed to create globals by accident. If you want to modify a global variable; you could use global keyword directly.

    • global is the most destructive: may affect all uses of the module anywhere in the program
    • nonlocal is less destructive: limited by the outer() function scope (the binding is checked at compile time)
    • no declaration (local variable) is the least destructive option: limited by inner() function scope

    You can read about history and motivation behind nonlocal in PEP: 3104 Access to Names in Outer Scopes.

提交回复
热议问题