Python’s global and nonlocal Keywords

Modifying Variables in Nested Scopes

Photo by Zach Graves on Unsplash

In the realm of Python programming, understanding variable scopes and their implications is crucial for crafting well-structured and maintainable code. Python employs a system of nested scopes, where inner functions have access to variables defined in their enclosing functions. However, directly modifying variables from outer scopes within inner functions can sometimes lead to unexpected behavior. This is where Python’s global and nonlocal keywords come into play, offering precise control over variable access and modification across nested scopes.

Understanding Variable Scopes in Python

Python adheres to the LEGB rule (Local, Enclosing, Global, Built-in) for determining variable scope. When an inner function attempts to access a variable, Python first searches within the local scope of the function itself. If not found, it looks in the enclosing scopes, then the global scope, and finally the built-in namespace. While accessing variables from outer scopes is straightforward, modifying them requires a nuanced approach.

The global Keyword

The global keyword explicitly declares that a variable within a function refers to a variable in the global scope. This allows you to directly modify a global variable from within a nested function. Let’s see this in action with an illustrative example:

Python

x = 10  # Global variable

def modify_global():
global x
x = 20
modify_global()
print(x) # Output: 20

In this example, without the global declaration, the assignment x = 20 would have created a new local variable x within the modify_global function, leaving the global x unchanged. By using global, we ensure that the assignment modifies the global variable.

The nonlocal Keyword

The nonlocal keyword, introduced in Python 3, is designed specifically for modifying variables in enclosing scopes (but not the global scope). It signals that a variable within a nested function refers to a variable in the nearest enclosing scope. Let’s illustrate this with an example:

Python

def outer_function():
x = 10
def inner_function():
nonlocal x
x = 20
inner_function()
print(x) # Output: 20
outer_function()

In this scenario, the nonlocal declaration within inner_function binds the variable x to the x defined in the outer_function, allowing its modification. Without nonlocal, a new local variable x would be created within inner_function, leaving the outer_function’s x unaffected.

Choosing the Right Keyword

  • Use global when you need to modify a variable in the global scope from within a nested function.
  • Use nonlocal when you need to modify a variable in an enclosing scope (not the global scope) from within a nested function.

Python’s global and nonlocal keywords offer elegant solutions for managing variable access and modification across nested scopes. By understanding their roles and applying them judiciously, you can enhance the clarity and maintainability of your Python code, especially when dealing with complex function interactions.

Remember, though powerful, these keywords should be used thoughtfully. Overuse of global variables can lead to code that is difficult to debug and maintain. Strive for a balance between leveraging their capabilities and adhering to best practices for clean and modular code design.

By mastering the intricacies of variable scopes and employing global and nonlocal effectively, you’ll empower yourself to write Python code that is both robust and adaptable.


Python’s global and nonlocal Keywords was originally published in ScriptSerpent on Medium, where people are continuing the conversation by highlighting and responding to this story.

Scroll to Top