A global variable is defined in a module’s global scope. Python resolves its name through the LEGB order: local, enclosing, global, then built-in scopes. section 10.4.1
A function call does not automatically update a global variable. An assignment inside the function creates or targets a local variable when that name is local under LEGB. section 10.4.2 section 10.4.4
Use global variables with these distinctions in mind:
- Read a global variable through normal name lookup when no local or enclosing binding takes precedence. section 10.4.1
- Declare a name with global inside a function before assigning to the module-level variable. section 10.4.2
- Inspect globals() and locals() to compare the module namespace with a function’s local namespace. section 10.4.2
- Organize module-level state alongside dependencies and interface-configuration functions when structuring an application script. section 14.4.8
Updating a database filename
db_filename = "N/A" def set_database(db_name): global db_filename db_filename = db_name set_database("tasks.sqlite") print(db_filename) # output: tasks.sqlite Without the global declaration, db_filename inside the function becomes a separate local variable. 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
View the complete successful assignment, including local-namespace output and the updated module-level value. section 10.4.2











