Mutating module state
A function must increment or replace a module-level state variable.
Python · Const
The global statement makes listed names refer to the module’s top-level namespace throughout the current scope. It is mainly needed when code inside a function assigns to a module-level variable.
Use global inside a function or other scope when an assignment must update a name in the module’s top-level namespace. The declaration applies throughout the current scope, so the name must not be read or assigned before its declaration there; at module level, global has no practical effect.
global identifier ("," identifier)*| Name | Type | Description |
|---|---|---|
identifier | identifier | One or more identifiers whose bindings should be treated as global in the current scope. |
counter = 0
def increment():
global counter
counter += 1
increment()
print(counter) # 1The function declares that assignments to counter target the module-level name, then increments it.
A function must increment or replace a module-level state variable.
Several names assigned in one function should resolve to module-level bindings.
A script function needs to update a top-level configuration or cache reference.
global tells Python to treat the listed names as bindings in the module’s top-level namespace rather than local bindings in the current scope. This allows an assignment such as counter += 1 inside a function to update the module-level variable.
Follow-up: What happens if the function only reads the name? A free variable can refer to a global without a global declaration; the declaration is needed for assignment in the current scope.
The declaration applies to the entire current scope, including a module, function body, or class definition. The listed name must not be used or assigned before its declaration in that scope.
Follow-up: Does global affect an enclosing function’s local variable? No. It refers to the top-level namespace, whereas nonlocal is used for a binding in an enclosing function scope.
At module level, names are already global, so global has no effect there. It still cannot be used after an earlier use or assignment of the same name in that module scope.
Follow-up: What about exec()? A global statement in code passed to exec applies only to that separately parsed code and does not change the containing block.
nonlocal statementexec()eval()compile()top-level namespace