What is the use of the "nonlocal" keyword in Python?

The nonlocal keyword in Python is used within nested functions to indicate that a variable being modified or referenced is located in an outer (enclosing) scope, but not in the global scope. It's used to deal with variables in situations where there are multiple levels of nested function scopes.

Here's the typical scenario where you would use the nonlocal keyword:

def outer_function():
    x = 10
    def inner_function():
        nonlocal x
        x = 20
    print(x)  # Output will be 20


In this example, the nonlocal keyword is used in the inner_function to indicate that the variable x being modified is the one in the outer scope of outer_function, not a new local variable in inner_function. This means that when inner_function modifies x, it's actually modifying the x in the outer_function scope, and the value of x becomes 20.

Here are some key points to note about the nonlocal keyword:

Scope Hierarchy: nonlocal works with nested functions, helping you access and modify variables in an outer (enclosing) scope, but not in the global scope.

Enclosing Scope: It's not used to access variables in the immediate global scope but rather in the nearest enclosing scope that's not global.

Mutability: nonlocal is particularly useful when dealing with mutable objects like lists or dictionaries, where you want to modify the same object in an outer scope.

Limitation: Unlike global, you can't use nonlocal to create a new variable in an outer scope if it doesn't already exist.

Python 3 Only: nonlocal is a feature introduced in Python 3. It's not available in Python 2.

In summary, the nonlocal keyword provides a way to work with variables in nested function scopes, allowing you to modify or reference variables in an outer scope that's not global. It's a useful tool when dealing with nested functions that need to interact with variables in their enclosing scopes.

Related Questions You Might Be Interested