Content · Programming · Python

Python nonlocal Keyword: Usage and Examples

nonlocal changes an existing binding in the nearest enclosing function scope rather than creating a new local. It is useful for closures that update their remembered state.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

This guide explains nonlocal keyword: usage and examples through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.

What You Will Learn


nonlocal changes an existing binding in the nearest enclosing function scope rather than creating a new local. It is useful for closures that update their remembered state.

When and Why to Use It


The following example focuses on a practical use of nonlocal Keyword: Usage and Examples.

Step-by-Step Example


def make_counter():
    count = 0
    def next_count():
        nonlocal count
        count += 1
        return count
    return next_count

counter = make_counter()
print(counter(), counter())

Understanding the Example


Both calls operate on the same count captured by that closure, yielding 1 and 2. A different make_counter call would create its own independent count.

Expected Output


1 2

Important Behavior and Edge Cases


nonlocal cannot create an enclosing binding that does not exist; it does not update a module-level global.

Try It Yourself


Create a counter with an adjustable step size and two independent instances.

Common Beginner Mistakes


  • nonlocal cannot create an enclosing binding that does not exist; it does not update a module-level global.
  • Confusing a returned value with printed output, or failing to verify a function’s behavior with different input values.
  • Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.

Key Takeaways


  • nonlocal changes an existing binding in the nearest enclosing function scope rather than creating a new local.
  • Both calls operate on the same count captured by that closure, yielding 1 and 2.
  • Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.
Share this resourceSend this page to someone who may find it useful.