Local Scope in Python

Overview

In Python, the term "local" refers to the scope within a function where variables are defined and resolved. It is the first level in the LEGB (Local, Enclosing, Global, Built-in) rule for variable resolution. This means that when a variable is referenced within a function, Python first looks for the variable in the local scope before moving on to other scopes.

Understanding Local Scope with Examples

Example 1: Local Variables

Consider the following code snippet:

db_filename = "N/A"

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

In this example, db_filename is initially defined in the global scope with the value "N/A". Inside the set_database function, a new local variable db_filename is created when it is assigned the value of db_name. The locals() function is used to print the local namespace, which shows the variables available in the function's local scope.

Example 2: Using the global Keyword

To modify a global variable within a function, the global keyword is used, as shown in the following 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/207)

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

In this example, the global keyword is used to indicate that db_filename refers to the global variable, not a new local one. This allows the function to update the global db_filename variable. After calling set_database("tasks.sqlite"), the global db_filename is updated to "tasks.sqlite", as confirmed by the subsequent print statement.

Debugging with locals()

When debugging, it can be useful to inspect the local scope to understand the current state of a function. The locals() function can be called directly in a debugger to list all variables in the local namespace:

(Pdb) locals()
{'inject_bug': True, 'task_text': 'Laundry,3#', 'title': 
 'Laundry', 'urgency_text': '3#'}

This output provides a snapshot of all variables within the function's local scope, offering a comprehensive view of the function's status at that point in execution.

FAQ (Frequently asked questions)

What is the first level in the LEGB rule for variable resolution in Python?