Python Nonlocal Keyword

In python, nonlocal keyword is useful to work with the variables inside nested functions. If you want to create a nonlocal variable in the inner function that should already exist in the outside function.

 

Generally, if you create a variable inside of the function, that variable scope is limited to within that function, but if you create the variable with a nonlocal keyword that variable scope is neither local nor global.

 

Following is the example of creating the nonlocal variable inside of the nested function using the nonlocal keyword in python.

 

def calculate():
    x = 10
    def add():
        nonlocal x
        x = x + 2
        print("Inside x val: {}".format(x))
    add()
    print("Outside x val: {}".format(x))
calculate()

If you observe the above example, we created a nonlocal variable x inside of the add() function using a nonlocal keyword.

 

When you execute the above python example, you will get the result as shown below.

 

Inside x val: 12
Outside x val: 12

The changes that we do for nonlocal variables will reflect in local variables. In python, if you try to create a nonlocal variable in the inner functions without existing that variable in outer functions, you will get an exception like no binding for nonlocal ‘x’ found.

 

Following is the example of creating the nonlocal variables inside of nested function in python.

 

def calculate():
    def add():
        nonlocal x
        x = 10
        x = x + 2
        print("Inside x val: {}".format(x))
    add()
    print("Outside x val: {}".format(x))
calculate()

If you observe the above example, we directly created a nonlocal variable (x) inside of the nested function (add).

 

When you execute the above python example, you will get an exception like as shown below.

 

Traceback (most recent call last):
File "variables.py", line 3, nonlocal x
SyntaxError: no binding for nonlocal 'x' found

This is how you can use nonlocal variables inside of nested functions to make required changes based on your requirements.