How can I use a global variable in a function?
Categories:
Mastering Global Variables in Python Functions

Understand how to effectively use and manage global variables within Python functions, exploring scope, best practices, and potential pitfalls.
In Python, variables have a scope that determines where they can be accessed and modified. Understanding variable scope is crucial for writing clean, predictable, and bug-free code. This article delves into how global variables interact with functions, covering the global
keyword, common use cases, and important considerations to avoid unexpected behavior.
Understanding Variable Scope in Python
Python primarily defines two types of variable scopes: local and global. A variable defined outside of any function or class is considered a global variable. It can be accessed from anywhere in the code, including inside functions. Conversely, a variable defined inside a function is a local variable, accessible only within that function.
When a function attempts to access a variable, Python follows the LEGB rule (Local, Enclosing function locals, Global, Built-in) to resolve its scope. If a variable is assigned a new value inside a function, Python by default treats it as a new local variable, even if a global variable with the same name exists. This behavior prevents accidental modification of global state, but it can be confusing if you intend to modify the global variable.
flowchart TD A[Start Program] --> B{Define Global Variable 'x' = 10} B --> C{Define Function 'my_func()'} C --> D{Inside 'my_func()'} D --> E{Is 'x' assigned a new value?} E -- Yes --> F[Create NEW Local 'x'] E -- No --> G[Access Global 'x'] F --> H[Function End] G --> H H --> I{Call 'my_func()'} I --> J[Program Continues]
Python Variable Scope Resolution Flow
Accessing Global Variables Without Modification
You can easily access and read the value of a global variable from within a function without using any special keywords. Python's LEGB rule ensures that if a local variable with the same name doesn't exist, the global variable will be used.
global_message = "Hello from global scope!"
def greet():
print(global_message) # Accessing global_message
def display_info():
local_data = "Local data here"
print(f"Global: {global_message}, Local: {local_data}")
greet()
display_info()
Accessing a global variable inside a function
Modifying Global Variables Using the global
Keyword
If you need to modify a global variable from within a function, you must explicitly declare it using the global
keyword. This tells Python that you intend to refer to the global variable, not create a new local one. Without global
, any assignment to a variable inside a function will create a new local variable, even if a global variable with the same name exists.
counter = 0
def increment_counter():
global counter # Declare intent to modify the global 'counter'
counter += 1
print(f"Inside function: {counter}")
print(f"Before call: {counter}")
increment_counter()
print(f"After call: {counter}")
# What happens without 'global'?
value = 10
def change_value():
value = 20 # This creates a NEW local 'value'
print(f"Inside change_value: {value}")
print(f"Before change_value: {value}")
change_value()
print(f"After change_value: {value}")
Using the global
keyword to modify a global variable
Best Practices and Alternatives
While the global
keyword provides a way to modify global variables, it's generally considered good practice to minimize its use. Here are some alternatives and best practices:
- Pass variables as arguments: The most common and recommended approach is to pass variables into functions as arguments and return modified values.
- Use classes and objects: For managing shared state, encapsulating data within classes is often a more robust and organized solution.
- Return values: Functions can return new values or modified versions of their inputs, which can then be assigned to global variables outside the function.
- Configuration modules: For application-wide settings, create a dedicated configuration module (e.g.,
config.py
) and import it. Variables in this module act like global constants.
# 1. Passing as arguments and returning
def increment_by_arg(num):
return num + 1
my_num = 5
my_num = increment_by_arg(my_num)
print(f"Incremented by arg: {my_num}")
# 2. Using a class
class AppState:
def __init__(self):
self.status = "running"
def stop_app(self):
self.status = "stopped"
app_state = AppState()
print(f"App status: {app_state.status}")
app_state.stop_app()
print(f"App status after stop: {app_state.status}")
# 3. Configuration module (conceptual)
# In config.py:
# DEBUG_MODE = True
# In main.py:
# import config
# if config.DEBUG_MODE:
# print("Debug mode is ON")
Alternatives to direct global variable modification
PI = 3.14159
.