The global statement declares that a variable name inside a function refers to the module-level (global) variable of the same name. Without this declaration, any assignment to a name inside a function creates a new local variable, even if a global variable with the same name exists. The syntax is global x (or global x, y, z for multiple names), placed anywhere in the function body before the first use.
The global statement is needed only for assignment to global variables. Reading a global variable works without any declaration — Python's LEGB rule automatically finds the name in the global scope if it is not defined locally. This asymmetry exists because Python needs to know at compile time (before the function runs) whether a name is local or global, and the presence of any assignment to a name within a function makes it local by default.
Overuse of global is considered a code smell. Mutable global state makes programs harder to reason about, test, and parallelise. Common alternatives include: passing values as function parameters and returning results, using instance attributes on objects, using module-level constants (by convention, UPPER_CASE names that are read but not reassigned), and using configuration objects. In well-structured Python code, global is rare.
Discussed in:
- Chapter 5: Functions — Scope and the LEGB Rule