The nonlocal keyword in Python

Overview:

  • The Python keyword nonlocal binds one or more variables to the outer scope. 
  • If the immediate outer scope does not have the same name present, it will resolve to the name in the next outer scope.
  • If none of the outer scopes have the same name present, it will resolve to global scope.
  • In the absence of nonlocal qualification, any variable is bound to its local scope.
  • Assume the program execution is at the inner most scope ('n' levels inside from a function call), the global keyword makes the name to be directly bound to global scope, while the nonlocal keyword makes the name to be bound to next outer scope at which the name is available.
  • A formal parameter of a function cannot be defined as nonlocal inside that function.

Example – Using nonlocal keyword:

# Example Python program using the Python keyword

# 'nonlocal'

val = 0

 

def f1():

    val = 5

   

    def f2():

        val = 7.5;

   

        def f3():

            nonlocal val;

            val = 10;

            print("f3:", val);

 

        f3();

        print("f2:", val);

   

    f2();

    print("f1:", val);

 

f1();

 

Output:

f3: 10

f2: 10

f1: 5

 

Example – Without using nonlocal keyword:

# Example Python program using the Python keyword 'nonlocal'

val = 0

 

def f1():

    val = 5

   

    def f2():

        val = 7.5;

   

        def f3():

            val = 10;

            print("f3:", val);

 

        f3();

        print("f2:", val);

   

    f2();

    print("f1:", val);

 

f1();

 

Output:

f3: 10

f2: 7.5

f1: 5

 


Copyright 2024 © pythontic.com