Blog

Filter posts by Category Or Tag of the Blog section!

nonlocal keyword usage in python

Sunday, 18 January 2015

In Python, the nonlocal keyword is used to access a variable defined in the nearest enclosing scope that is not the global scope. This means that it allows you to modify a variable that is defined in a scope outside of the current function.  Look at the following example:

 


def outer_function():

    x = "outer"



    def inner_function():

        nonlocal x

        x = "inner"



    inner_function()

    print(x)



outer_function()

 

In this example, we have defined two functions: outer_function and inner_function. The variable x is defined in the outer_function and initialized to "outer". The inner_function modifies the value of x to "inner" using the nonlocal keyword, which allows it to access the x variable defined in the outer_function. When we call outer_function, it prints the value of x, which is now "inner" because it was modified by inner_function.

 

It is important to note that nonlocal can only be used to access a variable in the nearest enclosing scope that is not the global scope. If there is no such variable defined, a SyntaxError will be raised. Additionally, the nonlocal keyword cannot be used to modify a variable in the global scope; in that case, you would need to use the global keyword instead. Here is another example: 
 

def outer_function():

    x = 10x



    def inner_function():

        nonlocal x

        x = x + 5

        print("Inner function: x =", x)



    inner_function()

    print("Outer function: x =", x)



outer_function()


By running the above code the output would be like this:
 

Inner function: x = 15

Outer function: x = 15

 

Category: Software

Tags: Python

comments powered by Disqus