Changing Variables in Python

In Python, changing variables across different scopes can be achieved using the global and nonlocal keywords. Understanding how these keywords work is essential for managing variable scope effectively. This page will explore how to change variables in different scopes, guided by the LEGB rule for variable resolution, and provide examples to illustrate these concepts.

Overview of Variable Scope

Python uses the LEGB rule to resolve variable names, which stands for Local, Enclosing, Global, and Built-in scopes. This rule determines the order in which Python searches for a variable name. When you need to change a variable in a different scope, you can use the global keyword for global variables and the nonlocal keyword for variables in an enclosing scope.

Changing Global Variables

To change a global variable from within a local scope, you use the global keyword. This keyword tells Python that a particular variable is defined in the global scope, allowing you to modify it from within a function. Here's an example:

Listing 10.8 Changing a global variable successfully

db_filename = "N/A"

def set_database(db_name):
   global db_filename
   db_filename = db_name
   print(list(locals()))

set_database("tasks.sqlite")
# [output: ['db_name']](https://livebook.manning.com/book/python-how-to/chapter-10/189)

print(db_filename)
# [output: tasks.sqlite](https://livebook.manning.com/book/python-how-to/chapter-10/189)

In this example, the set_database function uses the global keyword to indicate that db_filename is a global variable. This allows the function to update db_filename in the global scope, changing its value from "N/A" to "tasks.sqlite".

Changing Enclosing Variables

The nonlocal keyword is used to change variables in an enclosing scope, which is a scope that is not global but is outside the current local scope. This is particularly useful in nested functions. Here's how it works:

Listing 10.9 Changing a nonlocal variable

def change_text(using_nonlocal: bool):
   text = "N/A"
   def inner_fun0():
       text = "No nonlocal"

   def inner_fun1():
       nonlocal text
       text = "Using nonlocal"
      
   inner_fun1() if using_nonlocal else inner_fun0()
   return text


change_text(using_nonlocal=False)
# [output: 'N/A'](https://livebook.manning.com/book/python-how-to/chapter-10/189)

change_text(using_nonlocal=True)
# [output: 'Using nonlocal'](https://livebook.manning.com/book/python-how-to/chapter-10/207)

In the change_text function, the variable text is defined in the local scope of change_text. The two inner functions, inner_fun0 and inner_fun1, have their own local scopes, with change_text's scope being their enclosing scope. By using the nonlocal keyword in inner_fun1, the function modifies the text variable in the enclosing scope, demonstrating how nonlocal can be used to change variables in nested functions.