How to Use Global Variables in Python (global Keyword)
Learn how global variables work in Python. Understand variable scope, local vs global namespaces, and how to modify variables using the global keyword.
Explanation
Understanding namespaces and variable scoping is critical to writing bug-free software in Python. Scope determines which parts of your program can access or modify a variable. A variable declared outside of all functions exists in the global scope and can be read anywhere in the module.
However, a problem arises when a function attempts to modify (reassign) a global variable. By default, when Python sees an assignment inside a function, it assumes that variable is local to the function. If you try to modify a global variable without declaring it as global, Python will create a local variable with the same name, leaving the global variable unchanged (or raise an `UnboundLocalError`).
To explicitly tell Python that you want to modify a variable in the global namespace rather than creating a local one, you must declare it using the `global` keyword inside the function. While using global variables is sometimes necessary, it is generally considered a bad practice in large software design because it makes state hard to track and debug.
Step-by-Step Implementation
- 1
Declare variables that need to be accessed globally outside of any function scope.
- 2
Read global variables inside any function without adding special declarations.
- 3
Use the global keyword (e.g., global counter) inside functions if you need to modify the global variable value.
- 4
Limit global variable usage to prevent scope confusion and namespace pollution.
Code Example
This script demonstrates reading global variables, the variable shadowing trap, and modifying global variables using the global keyword.
counter = 10 # Global variable
def read_counter():
# Reading a global variable works out-of-the-box
print("Reading global counter:", counter)
def shadow_counter():
# Attempting to assign without 'global' creates a local variable
counter = 20 # Shadowing
print("Inside shadow function:", counter)
def modify_counter():
global counter # Declaring we are writing to global scope
counter = 50
print("Inside modify function:", counter)
read_counter()
shadow_counter()
print("Counter after shadow function:", counter) # Remains 10
modify_counter()
print("Counter after modify function:", counter) # Now 50Reading global counter: 10
Inside shadow function: 20
Counter after shadow function: 10
Inside modify function: 50
Counter after modify function: 50Frequently Asked Questions
What is variable shadowing in Python?
Shadowing occurs when a variable declared inside a local scope (like a function) has the same name as a variable in an outer global scope. The local variable masks the global one, making it temporarily inaccessible inside that scope.
What is the difference between global and nonlocal keywords?
global is used to access variables defined in the outermost module scope. nonlocal is used inside nested functions to access variables defined in the enclosing (outer) function scope.
Related How-To Guides
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Variables & Data Types Explained
Understand Python variables and core data types (strings, integers, floats, booleans). A complete beginner guide to memory assignment in Python.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.