Home·Error messages

python 3.11+ · Python

The message

UnboundLocalError: cannot access local variable 'count' where it is not associated with a value

What it means

If a function assigns to a name anywhere in its body, Python treats that name as local to the function — and you read it before the assignment ran. It shows up when you expected the outer value of the same name to be visible, or the first time you write a read-and-write operation such as count += 1. Initialising it inside the function with count = 0 is the usual answer; if you really must change the module-level value, global count does that, at the cost of a value whose writers become hard to trace. Up to 3.10 the same error read 'local variable referenced before assignment'.

The fix

There is no one-line command for this. The explanation says what to look at instead.

Printed by
python 3.11+
Python
18

A Python traceback splits the answer in two — the last line says what went wrong, the frames above it say where — so reading only the last line gives you the name and loses the place, and for the value-is-missing errors such as NoneType and KeyError the cause almost always sits in a frame above the one that crashed.

Reading an error message

  • Read from the first line down. The lower you go the more it is about the tool’s internals; the cause is usually at the top.
  • If there is a file and a line number, start there — not the top stack frame, but the topmost line that names a file you wrote.
  • Search the message verbatim, but strip your own paths and variable names first; those are what stop the search from matching.
  • The same condition is worded differently across tool versions. If results look wrong, add the version number to the query.
  • Before pasting a fix, check what it throws away. Some of these cannot be undone.

Common questions

Q. What does “UnboundLocalError: cannot access local variable 'count' where it is not associated with a value” mean?

If a function assigns to a name anywhere in its body, Python treats that name as local to the function — and you read it before the assignment ran. It shows up when you expected the outer value of the same name to be visible, or the first time you write a read-and-write operation such as count += 1. Initialising it inside the function with count = 0 is the usual answer; if you really must change the module-level value, global count does that, at the cost of a value whose writers become hard to trace. Up to 3.10 the same error read 'local variable referenced before assignment'.

Q. How do I fix it?

There is no one-line command. The explanation above says what to look at instead.

Q. Which tool prints this?

python 3.11+. It sits under Python, and the message runs to 14 words.

Errors nearby