The addition of nested function scopes made the variable lookup rules more complex:
- A reference
xlooks for the name
xfirst in the current local scope (function), second in the local scopes of the enclosing functions (inner to outer), third in the current global scope (the module file), and fourth in the built-in scope (Note: global declarations make the search begin in the global scope).
- An assignment,
x = 2for example, creates or changes the name
xin the local scope. If
xis declared global within the function, the assignment creates or changes the name
xin the enclosing module’s scope. If
xis declared nonlocal within the function the assignment changes the name
xin the closest enclosing function’s local scope (applies for Python3).
>>> x = 2 >>> def function1(): ... x = 3 ... def function2(): ... print(x) ... function2() ... >>> function1() 3