Global Variables
Understanding Scope
A global variable is defined outside of all functions and is accessible throughout the module. Functions can read global variables directly, but modifying them requires special handling.
count = 0 # Global variable
def increment():
print(count) # Can read global
increment() # Output: 0
0
The global Keyword
The global keyword allows a function to modify a variable declared outside its scope. Without it, Python creates a new local variable instead of modifying the global one.
total = 0
def add_to_total(amount):
global total # Declare we're using the global variable
total += amount
print(f"Total is now {total}")
add_to_total(10)
add_to_total(20)
Total is now 10 Total is now 30
Best Practices
Global variables should be used sparingly. They are more suitable for constants or configuration values than for frequently updated state. The table below shows recommendations.
Do | Don't |
---|---|
Use for constants | Use for frequently changed state |
Make names uppercase | Rely on them for function communication |
Document thoroughly | Use across many unrelated modules |
Consider alternatives | Use as default function parameters |
Alternatives to global variables include:
- Class attributes
- Function parameters and return values
- Configuration objects or modules
- Singleton or dependency injection patterns
Advanced Patterns
In larger applications, global-like values are often managed through configuration modules. This improves readability and avoids scattering global state across files.
# Config module pattern
# config.py
DEBUG = True
API_KEY = '12345'
# main.py
import config
def connect():
if config.DEBUG:
print("Debug mode enabled")
# Use config.API_KEY here
# Runtime modification
import config as cfg
cfg.DEBUG = False