liveBook · Manning

Global variable

As explained in Python How-To

A global variable is a variable defined in a module's global scope and accessible according to the language's name-resolution rules.

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

How Python How-To covers it

How deep it goes
Explains module scope, LEGB lookup, namespace inspection, and the global declaration, but stops short of broader state-management alternatives.
Examples
Demonstrates database filenames, globals() and locals(), and an application database option changed by set_db_option.
What it assumes
Assumes basic Python variables and functions while teaching scope, namespaces, and LEGB name resolution.
What you can do after
Apply it via Python’s global keyword to update module-level state from a function and diagnose accidental local assignments.
How it connects
Connects global variables with modules, global scope, local scope, namespaces, functions, and the LEGB rule.

Also explained in

Compare how 12 books explain global variable →

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.