Tag Archives: nested functions Python

Scopes and Nested Functions

The addition of nested function scopes made the variable lookup rules more complex:

  • A reference x looks for the name x first 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 = 2 for example, creates or changes the name x in the local scope. If x is declared global within the function, the assignment creates or changes the name x in the enclosing module’s scope. If x is declared nonlocal within the function the assignment changes the name x in the closest enclosing function’s local scope (applies for Python3).

Example 1:

>>> x = 2
>>> def function1():
...     x = 3
...     def function2():
...             print(x)
...     function2()
... 
>>> function1()
3

Continue reading