According to the python tutorial, functions look for variable names in the symbol tables of enclosing functions before looking for global functions:
The
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:
def receiving_function(f):
f()
def parent_function():
y = 10
def child_function():
print(y)
receiving_function(child_function)
will print 10
as 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 the receiving_function
along with the non-local variable y
.