global
The global keyword lets you declare that a variable inside a function refers to a variable at the module (global) scope, not a local variable. This allows you to modify global variables from within functions.
Syntax
global variable_name
You can declare multiple global variables by separating them with commas:
global x, y, z
How It Works
By default, variables assigned inside a function are local to that function. The global keyword tells Python to use the variable from the enclosing module scope instead:
# Without global - creates a local variable
def without_global():
x = 10
print(x) # 10
x = 5
without_global()
print(x) # 5 (global x unchanged)
# With global - modifies the global variable
def with_global():
global x
x = 10
print(x) # 10
x = 5
with_global()
print(x) # 10 (global x modified)
Common Use Cases
Configuration values
MAX_CONNECTIONS = 100
def increase_limit():
global MAX_CONNECTIONS
MAX_CONNECTIONS += 10
print(MAX_CONNECTIONS) # 100
increase_limit()
print(MAX_CONNECTIONS) # 110
Caching or memoization
_cache = {}
def get_cache(key):
return _cache.get(key)
def set_cache(key, value):
global _cache
_cache[key] = value
Counters
click_count = 0
def on_click():
global click_count
click_count += 1
print(f"Clicks: {click_count}")
on_click() # Clicks: 1
on_click() # Clicks: 2
on_click() # Clicks: 3
Why Use global?
Global variables are generally discouraged in favor of:
- Passing values as arguments
- Returning values from functions
- Using classes to encapsulate state
However, global is useful for:
- Simple scripts and prototypes
- Module-level configuration that needs to be modified
- Compatibility with legacy code
Best Practice
Instead of global, consider passing state explicitly:
# Prefer this
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
# Or this
def increment(counter):
counter["count"] += 1
Gotchas
Forgetting to declare global
counter = 0
def increment():
counter += 1 # UnboundLocalError!
increment()
This raises UnboundLocalError because Python sees an assignment to counter and treats it as a local variable. Use global counter before the assignment.
Reading without declaring
value = 10
def read_value():
print(value) # Works fine - just reading
def modify_value():
global value # Need this to modify
value = 20
Reading a global variable works without declaring global — you only need it when modifying.
See Also
- def-keyword — define functions
- globals built-in — return global namespace
- locals built-in — return local namespace