nonlocal

KeywordPython 3.0+Advanced

Declares a variable inside a nested function as belonging to the enclosing scope

Quick Info

Documentation
Official Docs
Python Version
3.0+

Learn by Difficulty

Quick Example

python
def outer():
    message = "hello"

    def inner():
        nonlocal message
        message = "goodbye"

    print(f"Before: {message}")
    inner()
    print(f"After: {message}")

outer()

# Practical: counter closure
def make_counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

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

nonlocal lets an inner function modify a variable from its enclosing function's scope, not the global scope.

Try in Playground

Tags

languagesyntaxcorescopeclosure

Related Items