Global Variables in Python Are Not That Global
Source: Dev.to
In the context of programming in the 1980s, “global variables” likely brings to mind languages like MBASIC. Today, using MBASIC as an example would be challenging, as it is now rarely used or known. Instead, GNU Bash—the default shell scripting language for many systems—will be used to illustrate what global variables were traditionally like. (Some might think of Fortran II, but I’m not familiar with it.)
Bash Example
a.bash
#!/bin/bash
. ./b.bash
. ./c.bash
. ./d.bash
init
print_count
inc
print_count
b.bash
inc() {
counter=$((counter + 1))
}
c.bash
print_count() {
echo $counter
}
d.bash
init() {
counter=1
}
Python Example
a.py
import c, b, d
d.init()
c.print_count()
b.inc()
c.print_count()
b.py
import d
def inc():
d.counter += 1
c.py
import d
def print_count():
print(d.counter)
d.py
def init():
global counter
counter = 1
Key Differences
As you can see, a global variable in Bash is truly global across files. In Python, however, a global variable is only global within its module (i.e., file). Mutating a global variable in Bash requires no special syntax, whereas in Python a function must explicitly declare global to modify a module‑level variable.
Consequently, although both are called “global variables,” Python’s are scoped to the module. This means they won’t interfere with variables in other modules unless we deliberately make them do so. For developers who use one class per module, a Python global variable behaves much like a class variable. Additionally, variable assignment inside a Python function is local by default, preventing accidental modification of global state unless explicitly intended.
In short, many traditional precautions about global variables in languages like Bash or MBASIC no longer apply in Python. Therefore, we might reconsider automatically rejecting global variables based on past advice and instead evaluate their use case thoughtfully.