How to Fix Python Global Variable Not Working
In this tutorial, you'll learn about How to Fix Python Global Variable Not Working. We cover key concepts, practical examples, and best practices.
Python treats variables assigned inside a function as local by default. Modifying a global variable without the global keyword creates a new local variable instead.
The Wrong Way
counter = 0
def increment():
counter = counter + 1 # UnboundLocalError
increment()
print(counter)
This produces:
Traceback (most recent call last):
File "script.py", line 6, in <module>
increment()
File "script.py", line 4, in increment
counter = counter + 1
UnboundLocalError: local variable 'counter' referenced before assignment
The Right Way
Declare the variable as global inside the function:
counter = 0
def increment():
global counter
counter = counter + 1
increment()
print(counter)
Output:
1
Step-by-Step Fix
1. Use the global keyword
count = 0
def reset():
global count
count = 0
def add(n):
global count
count += n
2. Use function attributes as an alternative
def increment():
increment.counter += 1
increment.counter = 0
increment()
print(increment.counter)
3. Use a class instead of globals
class Counter:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
c = Counter()
c.increment()
print(c.value)
4. Return and reassign
counter = 0
def increment(counter):
return counter + 1
counter = increment(counter)
print(counter)
5. Use a mutable container
counter = [0]
def increment():
counter[0] += 1
increment()
print(counter[0])
Prevention Tips
- Avoid global variables -- use function parameters and return values.
- Use classes to group related state.
- Use the
nonlocalkeyword for closures instead of globals. - Pass mutable objects as parameters instead of using globals.
- Use modules with module-level configuration objects.
Common Mistakes with global variable
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro