Quick answer: Python decided the name is a local variable of the function, and the line that failed read it before any assignment had run. The usual cause in a game is changing a module-level variable such as score inside a function without declaring global score. The other causes are a variable assigned only inside an if or event branch, a loop variable when the loop ran zero times, the name from except ... as err used after the block, and a local name that shadows a module or built-in.
Your game runs, a coin is collected or a key is released, and the window closes with an UnboundLocalError that names a variable you can see defined a few lines up. The message changed in Python 3.11, so two different sentences describe the same problem. This guide gives both wordings, explains the scoping rule that produces the error, and goes through the five ways game code runs into it, each with a broken example and its fix.
- The exact error
- The rule behind it
- The five common causes
- How to find which one you have
- Fix 1: changing a module-level variable from a function
- Fix 2: give the variable a value on every path
- Fix 3: the name after “except ... as”
- Fix 4: a local that shadows a module, function or built-in
- How to confirm the fix, and catch the next one early
- Seeing it when it happens on a player’s machine
- Related guides
- Frequently asked questions
The exact error
Python 3.11 and later:
Traceback (most recent call last):
File "game.py", line 42, in <module>
on_coin_collected()
File "game.py", line 9, in on_coin_collected
score += 10
^^^^^
UnboundLocalError: cannot access local variable 'score' where it is not associated with a value
Python 3.10 and earlier print the older sentence for the same situation:
UnboundLocalError: local variable 'score' referenced before assignment
UnboundLocalError is a subclass of NameError. A plain NameError: name 'score' is not defined means Python found no such name anywhere. UnboundLocalError is more specific: the name exists as a local variable of the current function, and it has no value yet.
The rule behind it
Python decides where each name lives when it compiles a function, before any line of it runs. The rule is short: if a function assigns to a name anywhere in its body, that name is local to the function for the whole body. That includes the lines above the assignment.
Assignment here means every form of binding: x = ..., x += ..., for x in ..., with ... as x, except ... as x, import x and def x inside the function.
Reading is different. A function that only reads a name it never assigns looks the name up in the enclosing function, then the module, then the built-ins. This is why the following works and misleads people into thinking module variables are freely available:
score = 0
def draw_hud(screen, font):
text = font.render(f"Score: {score}", True, "white") # reading: fine
screen.blit(text, (10, 10))
Add one assignment to score anywhere in draw_hud and the read on the first line breaks, because score is now a local that has not been given a value. Python does not fall back to the module variable. You can see the compiler’s decision in the function’s code object: on_coin_collected.__code__.co_varnames lists 'score' among the locals.
Calling a method on an object is a read of the name, so it never triggers the rule. bullets.append(b) works without any declaration. bullets = [] and bullets += [b] are assignments and make bullets local.
The five common causes
| Cause | Typical line that fails | Fix |
|---|---|---|
| Assigning to a module-level variable inside a function | score += 10, lives -= 1, paused = not paused | global, or pass the value in and return it, or keep state on an object |
| Variable assigned only in some branches | player.x += dx after an if/elif on key state | Give it a default before the branch |
| Loop variable when the loop body never ran | print(index + 1) after for index, wave in enumerate(waves) | Initialize before the loop, or do not use the loop variable afterwards |
Name from except ... as err used after the block | print(err) below the try statement | Copy what you need to another name inside the block |
| Local name shadows a module, function or built-in | max = max(a, b), random = ... after random.randint() | Rename the local variable |
How to find which one you have
The last frame of the traceback names the function and the line, and the message names the variable. From Python 3.11 the caret marks the exact read that failed. Then:
- Search that one function for every place the name is bound:
=,+=,for,as,import. There is always at least one, or the error would be a plainNameError. - If the same name also exists at module level and you meant that one, you have cause 1.
- If the assignments are all inside
if,elif,for,while,tryormatchblocks, ask which path through the function skips all of them. That path is the one that just ran (causes 2 and 3). - If the name appears after
asin anexceptclause, you have cause 4. - If the name is also something you import or call (
random,time,max,clamp), you have cause 5.
Errors of the second and third kind are often intermittent. The function works every time a key is held or an enemy is on screen, and fails on the one frame where nothing matched. That is a property of the input, so test the empty case on purpose: no keys pressed, an empty enemy list, a missing settings file.
Fix 1: changing a module-level variable from a function
Broken:
score = 0
bullets = []
def on_coin_collected():
score += 10 # UnboundLocalError
def reset():
score = 0 # no error, and no effect: this creates a new local
bullets = []
score += 10 means score = score + 10. The assignment makes score local, and the read on the right-hand side finds no value. reset() shows the quieter form of the same mistake: a plain assignment raises nothing and changes nothing outside the function.
The smallest fix is a global statement at the top of each function that assigns to the name:
def on_coin_collected():
global score
score += 10
def reset():
global score, bullets
score = 0
bullets = []
global is needed only in functions that assign. It is a declaration for the compiler and has to appear before the first use of the name in the function.
For a variable in an enclosing function (a closure), the keyword is nonlocal:
def make_combo_counter():
combo = 0
def hit():
nonlocal combo
combo += 1
return combo
return hit
A handful of globals is fine in a small Pygame project. Past that, two other shapes scale better. The first is to pass state in and return the new value, which keeps the function testable:
def add_points(score, amount):
return score + amount
score = add_points(score, 10)
The second is a game-state object. Assigning to an attribute leaves the bare name self untouched, so the scoping rule never applies:
class Game:
def __init__(self):
self.score = 0
self.lives = 3
self.bullets = []
def on_coin_collected(self):
self.score += 10
game = Game()
game.on_coin_collected()
If you already use a class and still get the error, look for a missing self.: score += 10 inside a method is cause 1 again.
Fix 2: give the variable a value on every path
Causes 2 and 3 are the same hole. Some route through the function reaches the read without passing an assignment, and the cure for both is a value set before the branch or loop begins.
Broken:
SPEED = 200
def move_player(player, keys, dt):
if keys[pygame.K_LEFT]:
dx = -SPEED * dt
elif keys[pygame.K_RIGHT]:
dx = SPEED * dt
player.x += dx # neither key held: dx was never assigned
Fixed:
def move_player(player, keys, dt):
dx = 0
if keys[pygame.K_LEFT]:
dx = -SPEED * dt
elif keys[pygame.K_RIGHT]:
dx = SPEED * dt
player.x += dx
The event loop produces the same bug. A value picked up inside for event in pygame.event.get(): exists only on frames where that event arrived:
def handle_events():
click_pos = None
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
click_pos = event.pos
return click_pos
Without the first line, any frame with no mouse click raises the error. With it, the caller gets None and has to check for it before indexing; using it unchecked gives the neighboring error covered in How to Fix “TypeError: ‘NoneType’ object is not subscriptable” in Pygame.
The loop that ran zero times
A for loop binds its variable on each iteration. If the sequence is empty, the variable is never bound:
def spawn_waves(waves):
for index, wave in enumerate(waves):
spawn(wave)
print("Spawned", index + 1, "waves") # waves == []: UnboundLocalError
Fixed by starting from a known value:
def spawn_waves(waves):
count = 0
for count, wave in enumerate(waves, start=1):
spawn(wave)
print("Spawned", count, "waves")
Search loops have the same hole when nothing matches:
def find_target(turret, enemies):
for enemy in enemies:
if turret.in_range(enemy):
target = enemy
break
return target # no enemy in range: UnboundLocalError
Return from inside the loop and state the no-match result explicitly:
def find_target(turret, enemies):
for enemy in enemies:
if turret.in_range(enemy):
return enemy
return None
Fix 3: the name after “except ... as”
Python deletes the name bound by except ... as err when the except block ends. This is documented behavior: the exception object holds a reference to the traceback, and clearing the name stops that from keeping the function’s frame alive. The effect is that err cannot be used after the block, even when the exception did occur:
DEFAULTS = {"volume": 0.8, "fullscreen": False}
def load_settings(path):
try:
with open(path) as f:
settings = json.load(f)
except (OSError, json.JSONDecodeError) as err:
settings = dict(DEFAULTS)
if settings == DEFAULTS:
print("Using defaults because:", err) # UnboundLocalError
return settings
Copy what you need into another variable while still inside the block, and initialize that variable first so the no-exception path has a value too:
def load_settings(path):
problem = None
try:
with open(path) as f:
settings = json.load(f)
except (OSError, json.JSONDecodeError) as err:
settings = dict(DEFAULTS)
problem = str(err)
if problem:
print("Using defaults because:", problem)
return settings
Fix 4: a local that shadows a module, function or built-in
This is cause 1 with a name you did not think of as a variable. Modules, functions and built-ins are all ordinary names, so assigning to one inside a function makes it local there:
import random
def spawn_enemy():
x = random.randint(0, 800) # UnboundLocalError: 'random'
random = x > 400 # this later line made 'random' local
return x, random
def end_round(points, high_score):
max = max(points, high_score) # UnboundLocalError: 'max'
return max
The message names random or max, which looks absurd until you find the assignment. Rename the local:
def spawn_enemy():
x = random.randint(0, 800)
on_right_side = x > 400
return x, on_right_side
def end_round(points, high_score):
best = max(points, high_score)
return best
Names worth avoiding for locals in game code because they collide with modules and built-ins you will call in the same function: time, random, math, max, min, round, id, type, input, list. An import statement inside a function is also an assignment, so import random halfway down a function makes random local for the lines above it.
The closure version of this error has its own wording. Reading a variable of an enclosing function before that function has assigned it raises NameError: cannot access free variable 'x' where it is not associated with a value in enclosing scope on Python 3.11 and later.
How to confirm the fix, and catch the next one early
Run the path that failed, and the empty variant of it: no keys held, no events in the queue, an empty list, a missing file. An UnboundLocalError appears only when the faulty line executes, so starting the game and seeing the menu proves nothing about a function that runs at game over.
Static checkers find most of these without running the game, because the rule is applied at compile time and they apply the same rule:
| Tool | What it reports |
|---|---|
| Pyflakes | local variable 'score' defined in enclosing scope on line 3 referenced before assignment |
| Ruff | F823 Local variable `score` referenced before assignment |
| Pylint | E0601 used-before-assignment, E0606 possibly-used-before-assignment (branches), W0631 undefined-loop-variable (loops) |
Pyflakes and Ruff catch causes 1, 4 and 5. The branch and loop cases need Pylint’s “possibly” checks or a type checker, since the code is valid on some paths. Running one of these on save in your editor removes most of this error class before the game starts.
Seeing it when it happens on a player’s machine
The branch and loop variants are the ones that ship, because they depend on input you did not try. An uncaught UnboundLocalError ends a Pygame program like any other exception. With the Bugnet Pygame SDK (pip install bugnet-sdk), bugnet_sdk.init(api_key) installs an exception hook that files the uncaught exception with its traceback, platform, OS version and game version, and waits for the upload before Python exits. The traceback gives you the function and line, which is all this error needs.
Two limits. The report’s title is the exception message, and reports with the same title stack into one entry with an occurrence count, so two different functions that both fail on a variable called dx land in the same entry; read the traceback of each occurrence before you close it. And Bugnet only sees errors that run: the hook reports the failing path after a player hits it, while a linter reports it before you ship. Use both. Setup is in the getting started guide.
Related guides
- How to Fix “TypeError: ‘NoneType’ object is not subscriptable” in Pygame
- How to Fix “AttributeError: ‘NoneType’ object has no attribute” in Pygame
- How to Fix “TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’” in Python Games
- How to Fix “AttributeError: module ‘pygame’ has no attribute ‘init’” (Shadowed Module Names)
- Python sys.excepthook for Pygame: Catch and Report Every Unhandled Exception
Frequently asked questions
What does “UnboundLocalError: cannot access local variable where it is not associated with a value” mean?
Python treats the name as a local variable of the function, because the function assigns to it somewhere, and the failing line read it before any assignment had run. It is the Python 3.11 and later wording of the older message “local variable referenced before assignment”.
Why do I get UnboundLocalError when the variable is defined at the top of my file?
The function assigns to that name, and score += 1 counts as an assignment, so Python creates a separate local variable for the whole function and never looks at the module-level one. Add global score at the top of the function, or pass the value in and return the new one.
Why can I read a global variable inside a function but not change it?
A name the function only reads is looked up in the module. A name the function assigns anywhere in its body is local for the entire body, so the module variable is no longer visible there. Method calls such as bullets.append(b) are reads and work without a global statement.
Is it bad to use global in a Pygame project?
No. A few globals in a small game are fine, and global is the correct fix for this error. As the game grows, keeping state on a Game object or passing values in and returning them is easier to test, and attribute assignments such as self.score += 1 are not affected by the scoping rule.
Why does the UnboundLocalError only happen sometimes?
The variable is assigned inside an if, a loop or an event branch, and the error appears on the path where none of those assignments ran: no key held, an empty list, no matching event. Give the variable a default value before the branch or loop.
Any assignment to a name inside a function makes that name local for the whole function. Declare global or nonlocal when you mean the outer variable, and give every other variable a value before the first branch or loop that could skip it.