Python Global Variables

In Python, understanding how variables behave in different scopes is essential for writing efficient and bug-free programs. One important concept in this context is the global variable.

In this article, we’ll cover:

  • What are global variables?
  • Difference between global and local variables
  • Using the global keyword
  • Best practices
  • Real-world examples

What Are Global Variables?

A global variable is a variable that is defined outside of a function and can be accessed anywhere in the code, including inside functions.

x = 10  # global variable

def print_value():
    print(x)

print_value()  # Output: 10

Here, the variable x is global because it is defined outside of any function and can be used within print_value().

Global vs Local Variables

A local variable is declared inside a function and can only be accessed within that function.

def my_function():
    y = 5  # local variable
    print(y)

my_function()
# print(y)  # This would cause an error

If a variable with the same name exists both globally and locally, the local variable takes precedence within the function.

x = 100

def my_function():
    x = 50
    print("Inside function:", x)

my_function()        # Output: 50
print("Outside function:", x)  # Output: 100

Modifying Global Variables Inside a Function

To modify a global variable inside a function, you must use the global keyword. Otherwise, Python will treat it as a new local variable.

Without global keyword:

count = 0

def increment():
    count = count + 1  # Error! UnboundLocalError

increment()

With global keyword:

count = 0

def increment():
    global count
    count += 1

increment()
print(count)  # Output: 1

The global keyword tells Python to use the globally declared variable, not a new local one.

Best Practices with Global Variables

Although global variables are accessible everywhere, overusing them can lead to code that is:

  • Hard to debug
  • Difficult to maintain
  • Prone to unexpected side effects

✅ When to use global variables:

  • Configuration values
  • Constants
  • Shared application state (sparingly)

❌ Avoid:

  • Using global variables to transfer data between functions
  • Modifying them frequently inside functions

Instead, prefer returning values from functions and using parameters for data exchange.

Real-World Example

Example: Using a global counter

counter = 0

def update_counter():
    global counter
    counter += 1
    print(f"Counter updated to: {counter}")

update_counter()
update_counter()

Output:

Counter updated to: 1
Counter updated to: 2

Explanation:

  • counter is initialized at 0.
  • The update_counter() function uses the global keyword to modify the counter variable declared outside the function.
  • Each time update_counter() is called, it increments counter by 1 and prints the new value.

Example: Global configuration

DEBUG_MODE = True

def log(message):
    if DEBUG_MODE:
        print(f"[DEBUG] {message}")

log("Application started")

Output:

[DEBUG] Application started

Explanation:

  • DEBUG_MODE is a flag that controls whether debug messages are printed.
  • The log() function checks this flag and prints the message with a [DEBUG] prefix if debugging is enabled.
  • This is a common and effective way to manage debug output in small scripts. For larger applications, consider using Python’s built-in logging module for more features (log levels, file logging, formatting, etc.).

Conclusion

Global variables in Python provide a way to share data across functions and modules. While they can be powerful, they should be used with caution. Favor local variables, function parameters, and return values to keep your code clean, predictable, and maintainable.

Understanding the use of the global keyword and scoping rules will help you write more efficient and bug-free Python programs.