Python global Keyword
Introduction
The global keyword in Python is used to modify a global variable from inside a function. Normally, when a variable is assigned a value inside a function, Python treats it as a local variable. If you want the function to work with a global variable instead, you must use the global keyword.
The global keyword is commonly used when multiple functions need to access and modify the same variable.
It is widely used in:
Automation testing
Application settings
Configuration management
Game development
Counters and trackers
State management
Software development
In this tutorial, you will learn about the Python global keyword, how it works, practical examples, real-world applications, common mistakes, and best practices.
What is the global Keyword?
The global keyword tells Python that a variable inside a function refers to a global variable rather than a local variable.
Example
count = 10
def update():
global count
count = 20
update()
print(count)
Output
20
The global variable count is modified inside the function.
Why Use the global Keyword?
Without the global keyword, Python creates a local variable inside the function.
Example
count = 10
def update():
count = 20
print(count)
update()
print(count)
Output
20
10
The global variable remains unchanged.
Syntax of global Keyword
General Syntax
global variable_name
Example
total = 100
def modify():
global total
total = 200
modify()
print(total)
Output
200
Modifying a Global Variable
Example
score = 50
def increase_score():
global score
score = score + 10
increase_score()
print(score)
Output
60
Updating Global Variables Multiple Times
Example
counter = 0
def increment():
global counter
counter += 1
increment()
increment()
increment()
print(counter)
Output
3
Reading Global Variables Without global
The global keyword is only required when modifying a global variable.
Simply reading a global variable does not require it.
Example
message = "Welcome"
def display():
print(message)
display()
Output
Welcome
Creating a Global Variable Inside a Function
The global keyword can also create a global variable from inside a function.
Example
def create_variable():
global username
username = "John"
create_variable()
print(username)
Output
John
The variable becomes available globally after the function executes.
Multiple Global Variables
Example
x = 10
y = 20
def update():
global x, y
x = 100
y = 200
update()
print(x)
print(y)
Output
100
200
Global Variables Across Multiple Functions
Example
balance = 1000
def deposit():
global balance
balance += 500
def withdraw():
global balance
balance -= 200
deposit()
withdraw()
print(balance)
Output
1300
Understanding UnboundLocalError
A common error occurs when Python treats a variable as local before it is assigned.
Incorrect Example
count = 10
def update():
count += 1
update()
Output
UnboundLocalError
Python assumes count is local because it is modified inside the function.
Correct Example
count = 10
def update():
global count
count += 1
update()
print(count)
Output
11
global Keyword in Automation Testing
Global variables are often used to store shared test data and configuration settings.
Example: Browser Configuration
browser = "Chrome"
def update_browser():
global browser
browser = "Firefox"
update_browser()
print(browser)
Output
Firefox
Example: Environment Configuration
environment = "QA"
def switch_environment():
global environment
environment = "Production"
switch_environment()
print(environment)
Output
Production
Example: Test Execution Counter
test_count = 0
def execute_test():
global test_count
test_count += 1
execute_test()
execute_test()
print(test_count)
Output
2
Real-World Example: Website Visitor Counter
visitors = 0
def visit():
global visitors
visitors += 1
visit()
visit()
print(visitors)
Output
2
Real-World Example: Inventory Update
stock = 100
def sell_product():
global stock
stock -= 1
sell_product()
print(stock)
Output
99
Real-World Example: Application Mode
mode = "Development"
def deploy():
global mode
mode = "Production"
deploy()
print(mode)
Output
Production
Common Mistakes Beginners Make
Forgetting the global Keyword
Incorrect
count = 5
def update():
count += 1
Output
UnboundLocalError
Overusing Global Variables
Using too many global variables can make programs difficult to understand and maintain.
Creating Unnecessary Global Variables
Avoid
global_value = 10
When a local variable would work better.
Using Globals for Temporary Data
Temporary calculations should usually use local variables.
Best Practices
Use global Only When Necessary
global total
Avoid unnecessary global modifications.
Prefer Function Parameters
def add(number):
return number + 1
Parameters are often cleaner than globals.
Use Meaningful Global Variable Names
application_version = "1.0"
Keep Global Variables Limited
Use them mainly for:
Constants
Configuration settings
Shared application state
Document Global Variables
Clearly explain their purpose in large projects.
Advantages of global Keyword
Allows modification of global variables
Enables shared data across functions
Useful for application-wide settings
Simplifies certain state-management tasks
Helpful for counters and trackers
Limitations of global Keyword
Can make code harder to debug
Increases coupling between functions
May create unexpected side effects
Reduces code maintainability when overused
Makes testing more difficult in large applications
Conclusion
The global keyword allows a function to modify a global variable instead of creating a new local variable. It is useful when multiple functions need to share and update the same data.
While the global keyword can simplify certain programming tasks, it should be used carefully because excessive reliance on global variables can make programs harder to understand, maintain, and debug.
In most situations, function parameters and return values provide a cleaner and more scalable solution. However, understanding the global keyword is essential for mastering Python variable scope and program structure.
Frequently Asked Questions (FAQs)
What is the global keyword in Python?
The global keyword allows a function to modify a global variable.
global count
When should I use the global keyword?
Use it when a function needs to modify a global variable.
Can I read a global variable without using global?
Yes.
message = "Hello"
def show():
print(message)
No global keyword is required.
What happens if I modify a global variable without global?
Python treats it as a local variable and may raise an UnboundLocalError.
Can I create a global variable inside a function?
Yes.
def create():
global username
username = "John"
Key Takeaways
The
globalkeyword allows functions to modify global variables.Global variables are defined outside functions.
Reading a global variable does not require
global.Modifying a global variable requires
global.The
globalkeyword can create global variables inside functions.Multiple functions can share and update global variables.
Forgetting
globalmay cause anUnboundLocalError.Overusing global variables can reduce maintainability.
Function parameters and return values are often better alternatives.
Understanding the
globalkeyword is essential for mastering Python variable scope.
