A scope is a visibility boundary for names. Its associated namespace contains the objects identified within that boundary, such as variables, functions, and classes. section 10.4.1
When Python resolves a name, it follows LEGB: Local, Enclosing, Global, then Built-in. A module supplies global scope; functions and classes create local scopes; a nested function sees its outer function’s scope as enclosing. section 10.4.1
Figure 10.8 The general process of resolving a variable: the LEGB rule. When Python encounters a variable, it tries to resolve it by looking up the local, enclosing (if applicable), global, and built-in scopes sequentially. If the variable is resolved, Python uses the value; otherwise, it raises a NameError.
Use the resolution diagram to trace each lookup from local through enclosing, global, and built-in scopes; unresolved names raise NameError. section 10.4.1
Changing a global name
An assignment inside a function creates or updates a local name when that name is not declared global. Declaring global db_filename makes the assignment update the module-level variable, so calling set_database("tasks.sqlite") changes the printed value from "N/A" to tasks.sqlite. section 10.4.2
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']
print(db_filename)
# output: tasks.sqlite
Run the complete database filename example to compare the successful global update with the function’s local namespace output. section 10.4.2
Changing an enclosing name
Nested functions form separate local scopes. Use nonlocal when an inner function must update a name belonging to its enclosing function; without it, text = "No nonlocal" creates a local name and leaves the enclosing text unchanged. section 10.4.3
Use scope inspection to understand and troubleshoot name behavior:
- Call locals() to inspect the variables registered in the current function scope. section 10.4.2
- Call globals() to inspect names registered in the module-level namespace. section 10.4.2
- Inspect locals() in a debugger to see the complete variable state at a paused line. section 13.2.4




















