Python - Nested Scope Examples


Consider the following code.

The code has a nested function definition.


X = 99                   # Global scope name: not used 
# w w w.j ava 2  s . c om
def f1(): 
    X = 88               # Enclosing def local 
    def f2(): 
        print(X)         # Reference made in nested def 

f1()                     # Prints 88: enclosing def local


f2 is a temporary function that lives only during the execution of the enclosing f1.

f2 is visible only to code in f1.

This enclosing scope lookup works even if the enclosing function has already returned.

For example, the following code defines a function that makes and returns another function:


def f1(): 
    X = 88 # from  w  w  w  .j  av  a 2s . co  m
    def f2(): 
        print(X)         # Remembers X in enclosing def scope 
    return f2            # Return f2 but don't call it 

action = f1()            # Make, return function 
action()                 # Call it now: prints 88


In this code, the call to action is really running the function we named f2 when f1 ran.

Related Topic