Global variables in Python
The global
keyword in Python allows you to declare that a variable modified inside a function is global, meaning it's defined at the script level and not only in the local scope of the function.
In other words, it allows a function to modify a variable defined outside of itself.
Syntax of the global keyword
Using global
is very simple:
global variable_name
This keyword must be written before any use or assignment of the variable in the function.
Why does it exist?
In Python, each function creates its own scope.
By default, a variable that is assigned in a function is local to that function. The global
keyword serves to break this barrier voluntarily to access a global variable.
Quick example
x = 5
def increase():
global x
x += 1
increase()
print(x) # Displays 6
In this example, without the global
keyword, the operation x += 1
would raise an error because Python would think we're trying to write a new local variable x
without having declared it.
If you forget to declare
global
, Python will think you're declaring a new local variable, and will raise an error if the global variable was supposed to be modified.
Global scope vs local scope
Type of scope | Where it lives | Who can modify it |
global | At the file/module level | Any function with global |
local | Inside a function | The function itself |
Limitations and dangers of global
Even though global
may seem convenient, its usage comes with many risks.
For example, let's talk about name collisions: if multiple functions modify the same global variable, the effects become unpredictable.
Another problem: it becomes difficult to know where a modified value comes from, especially in large files. We therefore have a problem of reduced readability.
Finally, the code becomes fragile. Any local change can have an impact on the entire program.
For example, this is a small trap that illustrates these dangers:
mode = "dev"
def toggle_mode():
global mode
mode = "prod"
def display_mode():
print(f"The mode is: {mode}")
toggle_mode()
display_mode() # "The mode is: prod"
Here, the entire program logic can change because of a single line in a function. 👀
Global variables can act like "time bombs" if they are modified in multiple places without discipline.
What are the alternatives to global?
Fortunately, Python offers several safer solutions than using global
.
Parameter passing
Rather than modifying a global variable, we can pass it as a parameter to a function, then retrieve the result:
def add(x):
return x + 1
total = 0
total = add(total)
With a return value
It's possible to return the new value and then assign it to the original variable:
def activate_debug():
return True
debug = False
debug = activate_debug()
With a class
Finally, we can also create a class to manage our variables:
class Counter:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
c = Counter()
c.increment()
print(c.value)
This is more clear, structured, scalable and perfect for long-term maintained code. 😋
The differences between local and nonlocal
The nonlocal
keyword allows you to modify a variable defined in an enclosing function (non-global). It's very useful in nested functions.
Keyword | Acts on: | Context |
global | Variable defined at the script level | Module/global file |
nonlocal | Variable defined in a parent function | Nested functions |
Let's take this example to better illustrate our point:
def outer():
counter = 0
def inner():
nonlocal counter
counter += 1
return counter
return inner()
print(outer()) # Result: 1
Here counter
is not global but it's declared in the parent function (outer
).
nonlocal
only works in nested functions. If you try to use it out of context, Python will raise an error.
The global keyword in modules
In a Python project composed of several files (main.py
, utils.py
, etc), the global
keyword acts only within the file (module) where it's defined.
Here's a small example! Let's imagine we have these two files:
config.py
option = "default"
main.py
from config import option
def change_option():
global option
option = "advanced"
change_option()
print(option) # ❌ Displays "advanced", but doesn't modify config.option
Here, option
in main.py
is copied from config.py
.
Using global
only modifies the variable local to the main.py
module.
Frequently asked questions about global
Can we declare multiple global variables at once?
Yes, just separate them with a comma:
global x, y, z
But be careful: this increases complexity and the risk of error. It's better to stay sober (except on Friday nights).
Should we initialize a global variable before using it in a function?
Yes, ideally. Even though Python gives this possibility to create a global variable from inside a function with global
, it makes the code less readable. It's much better to initialize all global variables at the beginning of the script.
What's the difference between
global
andglobals()
?
It's quite simple to understand: global
is a keyword used in a function to signal that you want to modify a global variable. Whereas globals()
is a function that returns the dictionary of all global variables in the module.
How to learn Python?
By following a good course! 🥸