Python 3
nonlocal keyword
Python programming
Python scopes
variable scope

What does nonlocal do in Python 3?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In Python 3, the nonlocal statement plays a critical role in managing variable scopes, particularly within nested functions. Understanding how nonlocal operates is essential for programmers looking to write more efficient and pythonic code, especially when dealing with closures or nested functions. This article will delve into the specifics of how the nonlocal statement functions, its differences compared to other scope-related statements like global , and its intended use cases.

Understanding Scope in Python

Before getting into the nuances of the nonlocal statement, it's important to understand the concept of scope in Python. Variables in Python can exist in different scopes, and Python generally has four types of variable scope:

  1. Local: Variables defined within a function and can only be accessed there.
  2. Enclosing: Variables present in the local scope of an enclosing function, applicable mainly to nested functions.
  3. Global: Variables defined at the top level of a module or declared with the global keyword within a function.
  4. Built-in: Variables that are pre-assigned in Python such as True , False , etc.

The nonlocal

Statement

The nonlocal statement is used to refer to variables in the nearest enclosing scope outside of the local scope that a function is defined in. This is particularly relevant when dealing with nested functions. With nonlocal , you can modify or update variables within an enclosing scope, but it does not apply to global variables.

Syntax

The basic syntax for nonlocal is as follows:

  • You have nested functions.
  • You need to modify a variable in an enclosing scope (not the global scope).
  • You wish to maintain stateful data without using instance variables in a class.
  • nonlocal : Only affects variables defined in an enclosing (non-global) scope.
  • global : Refers to variables in the module level, making it possible to read or overwrite global variables.
  • Nonexistent Enclosing Variables: Attempting to declare a nonlocal variable that doesn’t exist in the enclosing scope will raise a SyntaxError .
  • Declarative: Just like global , nonlocal must be declared before it is used in an assignment within the function.
  • Performance: Using nonlocal is a lightweight way to handle mutable state, especially for function-level encapsulation.
  • Alternative: If the use of nonlocal feels complex, especially for managing states, consider using closures or object-oriented approaches.

Course illustration
Course illustration

All Rights Reserved.