Mastering Python’s Global Keyword: How and When to Use It
Mastering Python’s Global Keyword: How and When to Use It
This guide explains the Python global keyword, its rules, practical use cases, and best practices for managing global variables across modules.
What Is the Global Keyword?
In Python, the global keyword lets you declare that a variable inside a function refers to a module‑level variable rather than a new local one. This is essential when a function needs to read or modify a variable that exists outside its own scope.
Rules for Using global
- Variables created inside a function are local by default.
- Variables defined at module level are global automatically;
globalis unnecessary when only reading them. - Use
globalinside a function when you intend to assign to a module‑level variable. - Placing
globaloutside a function has no effect.
Practical Use of global
Below are illustrative examples that demonstrate both the pitfalls and the correct approach.
Example 1: Accessing a Global Variable From Inside a Function
c = 1 # global variable
def add():
print(c)
add()
Output:
1
Here, c is read successfully because no assignment occurs inside add().
Example 2: Attempting to Modify a Global Variable Without global
c = 1 # global variable
def add():
c = c + 2 # attempts to modify c
print(c)
add()
Output:
UnboundLocalError: local variable 'c' referenced before assignment
The error occurs because Python treats c as a new local variable that is referenced before assignment.
Example 3: Modifying a Global Variable Using global
c = 0 # global variable
def add():
global c
c = c + 2
print("Inside add():", c)
add()
print("In main:", c)
Output:
Inside add(): 2 In main: 2
By declaring global c, the function updates the module‑level c, and the change is visible outside the function.
Sharing Global Variables Across Python Modules
For larger applications, it’s common to centralize configuration in a dedicated module, such as config.py. Other modules can import and modify these values, enabling consistent state across the program.
Example 4: Cross‑Module Global Variables
Create config.py:
a = 0
b = "empty"
Create update.py to modify the globals:
import config
config.a = 10
config.b = "alphabet"
Create main.py to verify the changes:
import config
import update
print(config.a)
print(config.b)
Output:
10 alphabet
This pattern keeps shared state in one place while allowing controlled updates from other modules.
Using global in Nested Functions
When a nested function needs to modify a variable that is local to an outer function, the global keyword can still be applied to create a truly global variable.
Example 5: Global Variable in a Nested Function
def foo():
x = 20
def bar():
global x
x = 25
print("Before calling bar:", x)
print("Calling bar now")
bar()
print("After calling bar:", x)
foo()
print("x in main:", x)
Output:
Before calling bar: 20 Calling bar now After calling bar: 20 x in main: 25
Inside foo(), x remains a local variable. The nested bar() declares x as global, so the assignment affects the module‑level x and is visible after foo() finishes.
While global can be handy, it’s generally best to design functions that return new values rather than mutate global state. This promotes clearer code and easier testing. For detailed language rules, see the official Python documentation on the global statement.
Python
- Mastering Python Data Types: A Practical Guide
- Mastering Python Operators: A Comprehensive Guide
- Mastering Python's While Loop: Syntax, Examples, and Best Practices
- Mastering the Python Pass Statement: A Practical Guide
- Understanding Python Global, Local, and Nonlocal Variables
- Python List Operations: Creation, Access, Modification, and Advanced Techniques
- Mastering Python Tuples: Creation, Access, and Advanced Operations
- Mastering Python Dictionaries: Creation, Manipulation, and Advanced Techniques
- Python Variables: Declaring and Managing String Types
- Python Variable Types: Understanding and Using Data Types