How can a function update a variable defined outside it? Use the global statement before assigning to that name. Without it, Python follows the LEGB rule and treats the assignment as creating a local variable. section 10.4.2 section 10.4.4
Update 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 The declaration changes the assignment target from the function's local scope to the existing global binding. section 10.4.2
A function argument such as db_name is local. If db_filename is assigned without global, both names appear in the function's local namespace, and the module-level value remains unchanged. Use global when the function must modify a global setting, such as the app_db database option. section 10.4.2 section 14.2.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
Inspect the complete working example, including the local namespace output and the changed global value. section 10.4.2


