How to use Python global keyword

Short answer:

In Python, a global variable is a variable declared outside any function, meaning it exists in the global scope. This makes it accessible from anywhere in our code, both inside and outside functions. However, while we can access a global variable inside a function, we can't modify it from within a function unless we explicitly use the global keyword with the global variable.

This lets us change the global variable inside our current function. It tells Python that when we use or update that variable, we're referring to the one defined globally, not the one inside the function.

When should we use Python global keyword?

In Python, variables created inside a function are local to that function and cannot be directly accessed outside of it. However, there are times when you might want to modify a variable that exists outside the function's scope (i.e., a global variable). This is where the global keyword becomes useful.

When we declare a variable with the global keyword inside a function, we're telling Python that we want to use the globally defined variable instead of creating a new local one. Once declared, we can modify the variable, and these changes persist outside the function.

Example of using the global keyword

Imagine we are working on an application where a global counter tracks the number of tasks completed. We might want to update this counter from various parts of your program, including within functions.

Without the global keyword, the following code will throw an error because we're trying to modify a variable outside the function’s scope:

completed_tasks = 0
def complete_task():
completed_tasks += 1 # Error! Python treats this as a local variable
print(f"Tasks completed: {completed_tasks}")
# Call the function multiple times
complete_task()
complete_task()
complete_task()

Python has raised an UnboundLocalError because it's trying to modify the completed_tasks variable without knowing it's defined globally.

Let's see what happens when we try to modify the same global variable within a function after declaring it as global. The example below demonstrates the use of global:

# Global variable to track the number of completed tasks
completed_tasks = 0
def complete_task():
global completed_tasks # Declare that we are using the global variable
completed_tasks += 1 # Modify the global variable inside the function
print(f"Tasks completed: {completed_tasks}")
# Call the function multiple times
complete_task()
complete_task()
complete_task()

In this example, the global keyword allows the complete_task function to modify the completed_tasks global variable, keeping track of the completed tasks across function calls.

Note: A variable cannot be declared global and assigned a value in the same line.

Declaration of global variable in Python
Declaration of global variable in Python

Using the global keyword in different scenarios

Let’s expand our task management example.

global keyword in for loops

Imagine you want to process tasks in a list and update the global counter as you complete them:

tasks = ["Task 1", "Task 2", "Task 3"]
# Global variable to track the number of completed tasks
completed_tasks = 0
# Function to process tasks and update the global completed_tasks variable
def process_tasks():
global completed_tasks # Declare that we are modifying the global variable completed_tasks
for task in tasks: # Iterate through each task in the tasks list
print(f"Processing: {task}") # Print the current task being processed
completed_tasks += 1 # Increment the completed_tasks count by 1 for each task processed
print(f"Total tasks completed: {completed_tasks}") # Print the total number of completed tasks
# Call the function to process the tasks
process_tasks()

In this case, the global keyword ensures that the completed_tasks variable is updated as tasks are processed.

global keyword in nested loops

What if you had tasks for different departments, and you wanted to process them using nested loops? Here’s how the global keyword works:

# Global variable to track the number of completed tasks
completed_tasks = 0
# Function to process batches of tasks and count "done" tasks
def nested_task_manager(task_batches):
global completed_tasks # Declare that we are modifying the global variable completed_tasks
for batch in task_batches: # Iterate through each batch in the task_batches list
for task in batch: # Iterate through each task within a batch
if task == "done": # If the task is marked as "done"
completed_tasks += 1 # Increment the completed_tasks count by 1 for each "done" task
print(f"All batches processed. Completed tasks: {completed_tasks}")
# List of task batches, each containing a series of tasks marked as "done" or "pending"
task_batches = [["done", "done"], ["pending", "done"], ["done", "pending"]]
# Call the function to process the task batches
nested_task_manager(task_batches) # Output: All batches processed. Completed tasks: 4

Again, the global keyword allows us to update the global completed_tasks variable while processing tasks from different departments.

Let us see a comprehensive example to sum up the functionality of the global keyword:

Before running the code, predict the output of each print statement. What will y be at each stage?

y = 1
def foo():
print ("Inside foo() : ", y) # uses global y since there is no local y
# Variable 'y' is redefined as a local
def goo():
y = 2 # redefines y in a local scope
print ("Inside goo() : ", y)
def hoo():
global y #makes y global and hence, modifiable
y = 3
print ("Inside hoo() : ",y)
# Global scope
print ("global y : ",y)
foo()
print ("global y : ",y)
goo()
print ("global y : ",y)
hoo()
print ("global y : ",y)

Try it yourself
Modify the code to answer the following questions:

  1. What happens if you remove the global keyword from hoo()?

  2. What happens if you add global y inside goo()?

  3. What happens if you declare y = 0 as a local variable inside foo()?

Key takeaways

  • Global access: The global keyword is not needed for printing and accessing, just for modifying.

  • Modifying global variables: Without global, any variable inside a function is treated as local, even if it has the same name as a global variable.

  • Practical use: The global keyword is useful when multiple functions need to work with the same variable, like a shared task counter or settings.

  • Best practice: Use global sparingly. Overusing global variables can make your code harder to debug and maintain.

Become a Python developer with our comprehensive learning path!

Ready to kickstart your career as a Python Developer? Our Become a Python Developer path is designed to take you from your first line of code to landing your first job.

This comprehensive journey offers essential knowledge, hands-on practice, interview preparation, and a mock interview, ensuring you gain practical, real-world coding skills. With our AI mentor by your side, you’ll overcome challenges with personalized support, building the confidence needed to excel in the tech industry.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


When should I use the global keyword in Python?

You should use the global keyword when you need to modify a global variable inside a function. Without it, Python will assume you’re working with a local variable, and the changes won’t affect the global scope.


Can I use the global keyword to create a global variable inside a function?

Yes! By using the global keyword, you can declare a new global variable from within a function. Once declared, the variable becomes accessible globally throughout the program.


Is it bad practice to use global variables in Python?

Using the global keyword in Python can be problematic because it makes debugging harder, reduces code readability, and creates tighter coupling between different parts of the code. It can also cause issues in multi-threaded environments, leading to race conditions. While global has its uses, it’s best to avoid it and use function parameters and return values to maintain cleaner, more manageable code.


What are the implications of using global with closures or in recursive functions?

Using global with closures: A closure is a function that captures the values of variables from its enclosing scope at the time of its creation. When a global variable is involved in closures, things can get tricky. Here’s why:

  • A global variable is shared across all scopes, so if a closure modifies a global variable, it will directly affect the global state, potentially leading to unexpected behavior if not carefully controlled.
  • Modifying global variables inside closures can break the encapsulation that closures provide and may lead to hard-to-debug issues in large codebases.

Using global in recursive functions: Using global in recursive functions can also be confusing and can lead to unintended consequences. Recursive functions often involve multiple calls, and if they modify a global variable, the variable’s state can change unexpectedly across different recursive calls.

  • Global state can accumulate changes as the recursive function progresses, which might not be desirable, especially if each recursive call should work independently.
  • For complex recursion, it’s often better to pass values as arguments and return updated values, rather than relying on global variables.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved