According to the python tutorial, functions look for variable names in the symbol tables of enclosing functions before looking for global functions:
The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.
What exactly does “enclosing function” mean, and when is it used?
I see the following code prints 10 when called
def parent_function():
y=10
def child_function():
print y
child_function()
However, calling child_function() alone produces an error. Are enclosing functions used frequently?
The concept of an enclosing function is key in understanding the idea of closures. Because python does not have fully featured lambdas (they only allow expressions and not statements), having nested functions to pass on to other functions is a common use case:
will print
10as before. This is a common instance of a closure, where the enclosing function “hands off” it’s variables to the enclosed function. In the example above, this function is passed off to thereceiving_functionalong with the non-local variabley.