How it works
global changes how bindings in the current code block are interpreted: the named variable belongs to the module namespace. It does not mean one variable is shared by every module or process.
Reading a module name does not require global. Mutating an object found through that name also differs from rebinding the name itself. Use the declaration before using or assigning the name within that block.
Choices and common mistakes
Shared mutable state makes call order matter. Prefer parameters and returned values unless module-level state has a clear purpose.
global supplies no locking, persistence or cross-process coordination. It is not a solution to concurrent updates.
Try it yourself
Compare a global counter with a function that accepts the current count and returns the next count. Explain which design makes independent tests easier.
Syntax
count = 0
def increment():
global count
count += 1Examples
Increment a module counter
Deliberately retain a counter between calls.
count = 0
def increment():
global count
count += 1
increment()
increment()
print(count)- global makes the assignment from += target the module binding. Each call reads the old integer and binds the next integer.
- The value survives calls because it is held by the module, not a new local variable.
- A small single-process demonstration can use this, but a production shared counter may require synchronization or external storage.
- Expected output: 2
Mutate without rebinding
Separate object mutation from assigning a name.
events = []
def record(message):
events.append(message)
record("started")
print(events)- record reads the module name events and invokes a method on the referenced list. It never assigns to the name events.
- The list changes in place, so global is unnecessary here. This is still shared state despite the missing declaration.
- Recognise mutation when reviewing code: lack of global does not guarantee a function is free of shared side effects.
- Expected output: ['started']
Return state explicitly
Offer a version whose dependencies are passed in.
def increment(count):
return count + 1
first = increment(0)
second = increment(10)
print(first, second)- count is a parameter local to each call. The function returns a new integer and leaves the caller responsible for storing it.
- The two calls are independent, so their results do not depend on execution history.
- Prefer explicit state for reusable calculations and straightforward unit tests.
- Expected output: 1 11
Best practices
- Shared mutable state makes call order matter. Prefer parameters and returned values unless module-level state has a clear purpose.
- global supplies no locking, persistence or cross-process coordination. It is not a solution to concurrent updates.
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference