liveBook · Manning

Global statement

As explained in Python Workout: 50 ten-minute exercises

The global statement declares that assignments and references to specified names in a function use the module-level global bindings.

A function normally creates a local variable when it assigns to a name. If the function must update the module-level binding instead, declare that name with global before retrieving or assigning it. section 6.5

Updating a module-level variable

x = 100 def foo(): global x x = 200 print(x) print(x) foo() print(x) The output is 100, 200, and 200: foo changes the existing global x rather than creating a separate local x. section 6.5

Without global, a function can use the same name locally without affecting the outer binding. Changing global state is usually discouraged, but can be necessary for an update such as a configuration parameter. section 6.5

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains declaration behavior with runnable examples and cautions against global mutation, without developing implementation internals.
Examples
Uses contrasting x bindings and a function that changes x through global.
What it assumes
Assumes functions and variable scope, while distinguishing local bindings from module-level bindings.
What you can do after
Apply it via Python to update a module-level binding from inside a function when necessary.
How it connects
Connects global statements with local variables, functions, closures, and lexical scope lookup.

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 Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.