0
0
PythonConceptBeginner · 3 min read

What is nonlocal in Python: Explanation and Examples

In Python, the nonlocal keyword allows you to assign a value to a variable in an enclosing (but not global) scope inside a nested function. It helps modify variables defined in the outer function from within an inner function.
⚙️

How It Works

Imagine you have a box inside another box. The inner box can see the outer box, but it cannot change what is inside unless you tell it explicitly. In Python, when you have a function inside another function, the inner function can read variables from the outer function but cannot change them by default.

The nonlocal keyword acts like a permission slip that lets the inner function change the variable in the outer function's box. Without nonlocal, if you assign a value to a variable inside the inner function, Python treats it as a new local variable, leaving the outer variable unchanged.

💻

Example

This example shows how nonlocal lets the inner function change a variable from the outer function.

python
def outer():
    count = 0
    def inner():
        nonlocal count
        count += 1
        return count
    print(inner())  # Prints 1
    print(inner())  # Prints 2

outer()
Output
1 2
🎯

When to Use

Use nonlocal when you want a nested function to update or modify a variable defined in its enclosing function. This is common in cases like counters, accumulators, or state trackers inside closures.

For example, if you write a function that returns another function which remembers how many times it was called, nonlocal helps keep that count updated.

Key Points

  • nonlocal modifies variables in the nearest enclosing scope, not global.
  • Without nonlocal, assigning to a variable inside a nested function creates a new local variable.
  • It is useful for closures that need to maintain or update state.

Key Takeaways

Use nonlocal to modify variables in an outer function from a nested function.
Without nonlocal, inner functions cannot change outer function variables.
nonlocal is helpful for maintaining state in closures or nested functions.