Skip to content

How to Fix Python Global Variable Not Working

DodaTech Updated 2026-06-24 2 min read

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 nonlocal keyword 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

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead 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

### Why does Python need the global keyword?

Python determines variable scope at compile time. If a variable is assigned anywhere in a function, it is treated as local throughout the function. The global keyword tells Python the variable lives at module scope.

What is the difference between global and nonlocal?

global refers to module-level variables. nonlocal refers to variables in an enclosing function scope (used in nested functions). nonlocal does not apply to global or local scopes.

Can I modify a global list without the global keyword?

Yes. Modifying the contents of a list (append, remove, etc.) does not reassign the variable name, so it does not require global. Only reassigning the name (list = [...]) requires global.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro