Question
How can you create or use a global variable inside a Python function?
How can a variable defined outside a function, or assigned in one function, be accessed from other functions?
A common issue is forgetting to use the global keyword when reassigning a global name inside a function, which can lead to UnboundLocalError.
For example:
count = 0
def increment():
global count
count += 1
def show():
print(count)
In this situation, what are the rules for reading and modifying global variables from functions in Python?
Short Answer
By the end of this page, you will understand what a global variable is in Python, how functions read and modify global names, when to use the global keyword, and why UnboundLocalError happens. You will also see safer alternatives that are usually better in real programs.
Concept
In Python, a global variable is a name defined at the module level, outside any function.
message = "Hello"
Here, message is global to that file.
Inside a function, Python follows name lookup rules to decide where a variable comes from. A function can usually read a global variable without any special keyword:
message = "Hello"
def greet():
print(message)
But if you assign to that name inside the function, Python treats it as a local variable unless you explicitly say otherwise.
message = "Hello"
def greet():
message = "Hi"
print(message)
In this case, message inside greet() is local, not global.
If you want to modify the global variable itself, you must use global:
message = "Hello"
def update_message():
global message
message = "Hi"
This matters because Python decides variable scope at compile time for the function body. If a name is assigned anywhere in the function, Python considers it local throughout that function, unless declared global or nonlocal.
That is why this code fails:
count = 0
def increment():
count += 1
Python reads count += 1 as:
count = count + 1
It sees an assignment to count, so it treats count as local. But then it tries to read the local count before it has a value, causing UnboundLocalError.
Global variables matter because they affect how data is shared across functions. However, in real programming, overusing globals can make code harder to understand, test, and debug. They are useful in some small scripts and configuration cases, but function parameters and return values are usually a better design.
Mental Model
Think of a Python file as an office building.
- A global variable is a notice board in the main lobby.
- A function is a private room.
- People inside a room can read the notice board in the lobby.
- But if they want to replace the notice on the lobby board, they must explicitly say: I am updating the lobby board.
That explicit statement is the global keyword.
Without it, if someone writes a new note inside the room, Python assumes it belongs only to that room.
So:
- Read only: you can look at the lobby board.
- Assign/update: you must declare
globalto change the lobby board. - Otherwise, Python assumes you are creating a room-only note.
Syntax and Examples
Basic syntax
Read a global variable
name = "Alice"
def show_name():
print(name)
This works because the function only reads name.
Modify a global variable
name = "Alice"
def change_name():
global name
name = "Bob"
This changes the module-level variable.
Example: reading vs writing
score = 10
def display_score():
print("Current score:", score)
def add_bonus():
global score
score += 5
display_score()
add_bonus()
display_score()
Output:
Current score: 10
Current score: 15
Why global is needed in add_bonus
score += 5 changes the variable, so Python needs to know that you mean the global score, not a new local one.
Example that causes UnboundLocalError
score = 10
def add_bonus():
score += 5
print(score)
This fails because Python treats score as local due to the assignment.
Creating a global variable from inside a function
def setup():
global config
config = {"debug": True}
setup()
print(config)
This works, but it is usually better to return values instead of creating globals inside functions.
Step by Step Execution
Trace example
count = 1
def increase():
global count
count = count + 2
def show():
print(count)
show()
increase()
show()
What happens step by step
-
count = 1- A global variable named
countis created.
- A global variable named
-
increase()is defined.- The function exists, but does not run yet.
-
show()is defined.- This function also exists, but does not run yet.
-
show()is called.- Python looks for
count. - There is no local
countinsideshow(), so it reads the globalcount. - It prints
1.
- Python looks for
-
increase()is called.global counttells Python thatcountrefers to the global variable.count = count + 2reads the current global value1.- It calculates
3. - It stores
3back into the globalcount.
-
show()is called again.- It reads the updated global
count. - It prints
3.
- It reads the updated global
Output
1
3
What if global is removed?
If increase() becomes:
def increase():
count = count + 2
then Python treats count as local because of the assignment. It tries to read that local count before it has been assigned, so it raises UnboundLocalError.
Real World Use Cases
Global variables do appear in real programs, but usually in limited, careful ways.
Common practical uses
Module-level configuration
DEBUG = True
API_URL = "https://example.com/api"
Functions may read these values across the file.
Shared constants
TAX_RATE = 0.15
MAX_RETRIES = 3
These are usually safe because they are not meant to change.
Small scripts
In a short automation script, a simple counter or status flag may be kept globally.
Caching or state in simple programs
A quick prototype may store a loaded resource in a global variable.
cache = {}
Where globals are less ideal
- Web applications
- Large codebases
- Multi-threaded programs
- Reusable libraries
- Unit-tested business logic
In these cases, passing data through parameters or using classes is usually clearer and safer.
Real Codebase Usage
In real codebases, developers usually try to avoid mutable global state because it creates hidden dependencies between functions.
Common patterns instead of globals
1. Pass values as parameters
def add_bonus(score):
return score + 5
This is easier to test and reuse.
2. Return updated values
def increment(count):
return count + 1
count = 0
count = increment(count)
3. Use configuration constants at module level
TIMEOUT = 30
def fetch_data():
print(f"Using timeout: {TIMEOUT}")
Reading constants globally is common.
4. Use objects to hold shared state
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
This is more structured than a mutable global variable.
5. Use guard clauses and validation with explicit inputs
def process_user(age):
if age < 0:
raise ValueError("age cannot be negative")
return age >= 18
This function does not depend on hidden external state.
When global is still used
- Tiny scripts
- Simple teaching examples
- Quick experiments in a single file
- Controlled module-level state
Even then, it should be used sparingly.
Common Mistakes
1. Reassigning a global without global
Broken code:
total = 0
def add():
total += 1
Problem:
- Python treats
totalas local because it is assigned inside the function. - It tries to read the local variable before assignment.
Fix:
total = 0
def add():
global total
total += 1
2. Thinking global is needed just to read a variable
Broken idea:
value = 10
def show():
global value
print(value)
This is not broken, but the global keyword is unnecessary here.
Better:
value = 10
def show():
print(value)
3. Creating too many globals
user = None
status = None
count = 0
items = []
mode = "test"
Problem:
- Many functions can change shared state.
- Bugs become harder to track.
Avoid this by passing values explicitly or grouping related state in a class or dictionary.
4. Confusing mutation with reassignment
This works without global:
items = []
def add_item():
items.append("apple")
Why? Because you are mutating the existing list, not reassigning the name items.
But this needs global:
items = []
def reset_items():
global items
items = []
Because now you are assigning a new object to the name items.
5. Using globals when return values are clearer
Less clear:
result = 0
def calculate():
global result
result = 5 * 5
Clearer:
def calculate():
return 5 * 5
result = calculate()
Comparisons
Global variables vs local variables
| Concept | Global variable | Local variable |
|---|---|---|
| Defined where | Outside functions | Inside a function |
| Visible where | Across the module | Only inside that function |
| Can be read in function | Yes | Yes, in its own function |
| Reassignment inside function | Requires global | No special keyword needed |
| Typical use | Constants, shared config, simple state | Temporary function data |
Reading vs modifying globals
| Action inside function | Needs global? | Example |
|---|---|---|
| Read value | No | print(count) |
| Reassign value | Yes | count = 5 |
| Augmented assignment | Yes | count += 1 |
| Mutate object | Usually no | items.append("x") |
global vs nonlocal
| Keyword | Used for | Scope affected |
|---|---|---|
global | Refer to a module-level variable | Global/module scope |
nonlocal | Refer to a variable in an enclosing function | Outer function scope |
Example of nonlocal:
def outer():
count = 0
def inner():
nonlocal count
count += 1
return count
return inner
Cheat Sheet
Quick rules
- A global variable is defined outside functions.
- You can read a global variable inside a function without
global. - You must use
globalif you assign to that global name inside the function. x += 1counts as assignment.- Mutating an object like
items.append()is different from reassigningitems.
Syntax
Read global
value = 10
def show():
print(value)
Modify global
value = 10
def change():
global value
value = 20
Create global inside function
def setup():
global config
config = {}
Common error
count = 0
def increment():
count += 1
Error:
UnboundLocalError
Fix:
def increment():
global count
count += 1
Best practice
Prefer:
- function parameters
- return values
- classes for shared state
- module-level constants for read-only values
Use globals sparingly.
FAQ
Why can I read a global variable in Python without using global?
Because reading does not create a local variable. Python looks for the name in local scope first, then outer scopes, then global scope.
Why does count += 1 need the global keyword?
Because it reassigns the name count. Python treats that as a local assignment unless you declare it as global.
Does modifying a list or dictionary require global?
Not if you are mutating the existing object, such as with append() or key assignment. But if you reassign the variable name to a new object, then yes.
Can I create a global variable from inside a function?
Yes, by using global, but it is usually better to return a value and assign it outside the function.
Is using global variables bad practice in Python?
Not always, but mutable globals are often discouraged because they make code harder to reason about and test.
What is the difference between global and nonlocal?
global refers to a module-level variable. nonlocal refers to a variable in an enclosing function.
How do I avoid UnboundLocalError with globals?
Use global when reassigning a global variable inside a function, or redesign the function to use parameters and return values instead.
Mini Project
Description
Build a small Python program that tracks how many tasks have been completed. This project demonstrates reading and updating a global variable from different functions, while also showing where global is required.
Goal
Create a task counter that can display the current count, increment it, and reset it.
Requirements
- Create a global variable to store the number of completed tasks.
- Write one function that displays the current count.
- Write one function that increments the count.
- Write one function that resets the count to zero.
- Call the functions to show that the global state changes across function calls.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Add Rows to a Pandas DataFrame in Python
Learn how to add rows to a Pandas DataFrame, why repeated row appends are slow, and when to use loc, concat, or record lists.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.