liveBook · Manning

Global statement

As explained in Python Workout, Second Edition

The global statement declares that assignments and name accesses in a function refer to a module-level global name.

Inside a function, assigning to a name normally creates or updates a local variable. Add `global name` when retrievals and assignments must use the module-level variable instead. section 7.5

x = 100

def foo():
    x = 200
    print(x)

print(x)
foo()
print(x)

Compare a local `x` with the module-level `x`; the function's assignment leaves the outer value unchanged. section 7.5

x = 100
def foo():
    global x
    x = 200
    print(x)
print(x)
foo()
print(x)

The `global x` declaration makes the function update the single module-level `x`, so the later print sees `200`. section 7.5

Use this sparingly: changing global state is almost always a poor choice, though updating a global configuration parameter can be necessary. Mutating an existing global list item or dictionary value does not require `global`. section 7.5

How Python Workout, Second Edition covers it

How deep it goes
Distinguishes local assignment from global assignment and explains why list or dictionary item mutation differs.
Examples
Uses contrasting `x` examples showing local shadowing and explicit global reassignment.
What it assumes
Assumes familiarity with functions, variables, and local-versus-global scope.
What you can do after
Apply it via Python syntax to update a module-level name from inside a function when necessary.
How it connects
Connects global variables with local variables, functions, scope, and mutable lists or dictionaries.

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, Second Edition. The section links point to the parts of the book it draws on.