What is the purpose of the ‘nonlocal’ keyword in Python?

This article explains the ’nonlocal’ keyword in Python, its importance, use cases and provides clear code examples to illustrate its functionality. …

Updated August 26, 2023



This article explains the ’nonlocal’ keyword in Python, its importance, use cases and provides clear code examples to illustrate its functionality.

Let’s dive into understanding the “nonlocal” keyword in Python.

Understanding Scope in Python

Before we tackle “nonlocal,” it’s crucial to grasp the concept of variable scope in Python. Essentially, scope dictates where a variable is accessible and usable within your code. Python has four levels of scope:

  1. Local: Variables defined inside a function have local scope. They exist only within that function and are inaccessible outside it.

  2. Enclosing: In nested functions (functions within functions), the inner function can access variables from the outer function. This is the enclosing scope.

  3. Global: Variables declared outside any function have global scope. They can be accessed from anywhere in your code.

  4. Built-in: These are pre-defined variables and functions available in Python (like print, len).

The ’nonlocal’ Keyword: Bridging the Gap

Now, imagine you have a nested function and want to modify a variable from the enclosing scope within the inner function. This is where “nonlocal” comes into play.

The “nonlocal” keyword tells Python that a variable inside an inner function should not be treated as local but instead refers to a variable in the enclosing function’s scope. It lets you modify variables in the outer function from within the nested one.

Why is This Important?

Understanding “nonlocal” empowers you to write more sophisticated and flexible Python code. It allows for data persistence across different levels of function calls, enabling complex logic and state management.

Example: Modifying a Counter

def outer_function():
    counter = 0  # Variable in the enclosing scope

    def inner_function():
        nonlocal counter # Declare 'counter' as nonlocal
        counter += 1
        print(f"Counter inside inner function: {counter}")

    inner_function()
    print(f"Counter after calling inner function: {counter}")

outer_function()

Explanation:

  1. outer_function defines a variable counter with initial value 0.

  2. inner_function is defined inside outer_function.

  3. The line nonlocal counter within inner_function is key. It tells Python that when we use “counter” inside inner_function, we’re referring to the counter variable from the enclosing outer_function.

  4. When inner_function increments counter, it’s actually modifying the counter defined in the outer function, not creating a new local variable.

Output:

Counter inside inner function: 1
Counter after calling inner function: 1

Importance for Learning Python

Learning about “nonlocal” helps you:

  • Understand Python’s scope rules in detail.
  • Write more complex and reusable functions with state persistence.
  • Avoid common errors related to variable access in nested functions.

Remember, the “nonlocal” keyword is a powerful tool for managing data flow in nested functions. Mastering it will significantly enhance your ability to write elegant and effective Python code.


Stay up to date on the latest in Computer Vision and AI

Intuit Mailchimp