Global Variables in Python
A global variable in Python is a variable declared at the top level of a module file, outside any function or class. It is accessible anywhere in that module after it is defined.
Defining a Global Variable
# global_var.py
RETRIES = 3
TIMEOUT = 30
user_count = 0
def show_config():
print(f"Retries: {RETRIES}, Timeout: {TIMEOUT}")
show_config() # Retries: 3, Timeout: 30
Functions can read global variables without any special keyword. They can see them because Python looks up names in the local scope, then the enclosing scope, then the global (module) scope.
Modifying a Global Variable Inside a Function
To change a global variable from inside a function, you must declare it with global:
counter = 0
def increment():
global counter
counter += 1
increment()
increment()
print(counter) # 2
Without global, this assignment would create a new local variable instead:
counter = 0
def broken_increment():
counter += 1 # UnboundLocalError
broken_increment()
This raises UnboundLocalError because Python sees the assignment and treats counter as local.
Global Variables vs Constants
By convention, constants — values that should not change — are written in UPPER_CASE:
MAX_CONNECTIONS = 50
DEFAULT_PORT = 8080
These are still technically mutable globals, but the naming convention tells other programmers not to change them.
Why Global Variables Are Discouraged in Larger Scripts
Global variables make code harder to reason about because any function can change them. In security scripts, this can lead to:
- Unexpected state changes across functions
- Harder unit testing
- Race conditions in multi-threaded tools
A better pattern is to pass values as arguments and return results:
def increment(counter):
return counter + 1
counter = 0
counter = increment(counter)
print(counter) # 1
For global configuration (file paths, ports, API URLs), it is often acceptable to use module-level constants, but keep them read-only where possible.
Related Concepts
- Python Essentials for Security Scripting — clean script structure and avoiding shared mutable state.
- Single Responsibility Principle in Security Scripts — why functions should avoid depending on hidden global state.
- Python Functions — scope, arguments, and return values.