How to declare a global variable in Python
A global variable in Python is a variable that can be accessed throughout the entire program, including within functions, classes, and other modules, as long as it is declared at the top level of the script or module. Here’s a detailed explanation of how to declare and use global variables in Python:
Declaring a Global Variable
To declare a global variable, simply define it outside of any function, loop, or class.
# Global variable
global_variable = "I am global"
This variable global_variable
is now accessible throughout the program.
Accessing a Global Variable
You can access a global variable directly inside functions and other parts of the program without any special declaration.
# Global variable
greeting = "Hello, World!"
def print_greeting():
print(greeting) # Access global variable
print_greeting() # Output: Hello, World!
Modifying a Global Variable Inside a Function
To change a global variable inside a function, you have to declare it as global
within the function. This makes Python understand that you are referring to the global variable and not defining a new local variable.
# Global variable
count = 0
def increment_count():
global count # Declare 'count' as global
count += 1 # Modify the global variable
increment_count()
print(count) # Output: 1
Without the global
keyword, Python would assume you’re creating a new local variable within the function.
Common Pitfalls
- Shadowing: If you declare a variable with the same name as a global variable inside a function without the
global
keyword, it creates a local variable that shadows the global one.
x = 10 # Global variable
def modify_x():
x = 20 # Local variable (does not affect global x)
print("Inside function:", x)
modify_x() # Output: Inside function: 20
print("Outside function:", x) # Output: Outside function: 10
2. Overuse: Using too many global variables can make your code harder to read, debug, and maintain. It’s generally better to pass variables as arguments to functions when possible.
Best Practices
- Use global variables sparingly.
- Prefer constants (global variables that don’t change) for configuration values.
- Use classes or modules to encapsulate global variables when they relate to specific functionalities.
- Use meaningful names and avoid accidental naming conflicts.
Example of Proper Usage
# Configuration variables (constants)
APP_NAME = "MyApp"
VERSION = "1.0"
def display_info():
print(f"Application: {APP_NAME}, Version: {VERSION}")
display_info()