liveBook · Manning

Global statement

As explained in Python How-To

The global keyword declares that assignments to a name in a function refer to the corresponding binding in the global scope.

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

How Python How-To covers it

How deep it goes
Explains LEGB resolution, local namespaces, and successful assignment without descending into interpreter internals.
Examples
Demonstrates changing db_filename and selecting the app_db database option.
What it assumes
Assumes basic functions and assignments, then develops namespaces and LEGB-based name resolution through examples.
What you can do after
Apply it to update a global variable from a function and diagnose why an unqualified assignment stays local.
How it connects
Connects global scope with local scope, namespaces, the LEGB rule, and the nonlocal keyword.

Also explained in

Compare how 3 books explain global statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.