Python - Nested Scope Examples

Introduction

Consider the following code.

The code has a nested function definition.

Demo

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

f1()                     # Prints 88: enclosing def local

Result

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:

Demo

def f1(): 
    X = 88 # from   www.ja v a 2s .c om
    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

Result

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

Related Topic