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
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?:
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 programnonlocal
is less destructive: limited by the outer() function scope (the binding is checked at compile time)You can read about history and motivation behind nonlocal
in PEP: 3104
Access to Names in Outer Scopes.