In the context of programming in the 1980s, "global variables" likely brings to mind languages like MBASIC. However, using MBASIC as an example today would be challenging, as it is now rarely used or known. Instead, GNU Bash, which is the default shell scripting language for many systems—will be used to illustrate what global variables were traditionally like. Anyway, some might think of Fortran II, but I'm not familiar with it.
Bash Example
I wrote a Bash script consisting of four files:
a.bash
a.bash orchestrates everything. "Orchestration" might be too grand a word for these toy scripts, but I want to convey that it performs a role similar to Apache Airflow.
#!/bin/bash
. ./b.bash
. ./c.bash
. ./d.bash
init
print_count
inc
print_count
b.bash
b.bash contains only one function, inc, which increments the counter, which is the global variable in this example.
inc() {
counter=$((counter + 1))
}
c.bash
c.bash contains print_count, which simply displays the value of the global variable counter.
print_count() {
echo $counter
}
d.bash
In Bash, counter can be initialized globally from within a function by default.
init() {
counter=1
}
Python Example
The following section shows the result of porting the Bash script above to Python, highlighting the key differences.
a.py
This is the orchestration part. Note the use of namespaces or module names.
import c, b, d
d.init()
c.print_count()
b.inc()
c.print_count()
b.py
In the Python version, inc must refer to the module d to access the variable. Alternatively, counter could be explicitly imported.
import d
def inc():
d.counter += 1
c.py
Similarly, print_count in Python must also refer to module d.
import d
def print_count():
print(d.counter)
d.py
Unlike in Bash, initializing a global variable from within a function—even in the same module—requires an explicit global declaration.
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. Furthermore, 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.
Top comments (0)