Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages

Node.js, PHP and APIs · Troubleshooting walkthrough

Python raises UnboundLocalError for a variable the function assigns

Short answer

UnboundLocalError: cannot access local variable 'content' where it is not associated with a value means content is assigned somewhere in the function, which makes it local everywhere there, but the read ran before any assignment: an if branch was skipped, a try failed, a loop was empty, or a global is shadowed. Bind it on every path. Python 3.11+ wording.

  • Applies to Python 3.11 and later (this wording), Python 3.10 and older: local variable 'content' referenced before assignment, pylint 4.1
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Python decides which names are local to a function before the function runs. The language reference says that if a name is bound anywhere in a code block, every use of it in that block refers to the local one. So one content = ... line, even at the bottom of the function or inside an if that never runs, makes content local from the first line, and reading it before that line has run raises UnboundLocalError.

The fix is never to rename the variable or add a try around the read. Find the path through the function that skips the assignment, then bind the name on that path too. Python 3.10 and older print the same error as local variable 'content' referenced before assignment.

The text you see

  • UnboundLocalError: cannot access local variable 'content' where it is not associated with a value
  • UnboundLocalError: local variable 'content' referenced before assignment

Stage 1

Ask the function which names it treats as local

Every function's code object lists its local names in co_varnames, parameters first. If the name from the error is in that tuple, Python compiled it as local and the module-level variable of the same name is invisible inside the function. That one check separates "the assignment was skipped" from "I thought this was the global".

content is local, so the global is never read

content = ""
def add_chunk(chunk):
    content += chunk

print(add_chunk.__code__.co_varnames)   # ('chunk', 'content')

Stage 2

Where the assignment sits decides the fix

Open the traceback's last frame, find every line in that function that assigns the name, and look at what wraps it. Each row below was run on Python 3.15 and printed the 3.11+ wording.

The only assignment isIt fails whenBind it by
inside an `if` (or `elif`) branchthe condition is false, such as a GET where the code expects POSTsetting a default before the `if`
the first line of a `try` blockthat call raised and the `except` only logged itreturning or raising in `except`, or using `else`
in a `for` loop bodythe iterable was emptysetting a default before the loop
`name += ...` on a module-level namealways, on the first callpassing the value in, or `global name`
`except Exc as name`you read `name` after the `except` blockcopying it to another name inside the block
followed later by `del name`a read comes after the `del`not deleting, or rebinding first

Stage 3

A branch that only one kind of request takes

The classic web version: a Flask view sets content only when the form is posted, then renders the template on every request. The first plain visit to the page is a GET, the if is skipped, and render_template reads a name that was never bound.

Default first, real value in the branch

@app.route("/", methods=["GET", "POST"])
def index():
    content = None                       # bound on every path
    if request.method == "POST":
        content = ask_model(request.form["prompt"])
    return render_template("index.html", content=content)

The template then has to cope with None; a {% if content %} around the output is enough.

Stage 4

A try block whose call raised

When the call inside try raises, the assignment on that line does not happen. An except that logs and carries on lets execution fall through to the read, so the log shows the real error (an API failure, a timeout) followed by this one. The second error is a symptom; the first is the thing to fix.

Make the except block end the path with return, raise or an explicit fallback value, and move the code that needs the result into else, which the compound statements reference says runs only when the try block raised nothing.

try:
    content = ask_model(prompt)
except APIError as exc:
    log.warning("model call failed: %s", exc)
    return render_template("index.html", error="The model call failed."), 502
else:
    return render_template("index.html", content=content)

Stage 5

A loop that had nothing to iterate

A for loop runs its body once per item. Code that keeps the last chunk of a stream or the last choice of an API response in a variable, then returns it after the loop, works on every normal answer and fails on the first empty one. Start with an empty value and decide what "no items" means for the caller.

content = ""
for choice in data.get("choices", []):
    content = choice["message"]["content"]
if not content:
    raise ValueError("the response had no choices")
return content

Stage 6

An augmented assignment that hides a global

content += chunk both reads and binds content, and the binding is enough to make the name local for the whole function. The Python programming FAQ walks through exactly this. Passing the value in and returning the new one keeps state out of module globals; use global (or nonlocal for an enclosing function) only when changing the outer name is the point.

def add_chunk(content, chunk):
    return content + chunk

Stage 7

Names Python removes for you

Two cases surprise people because no assignment was skipped. The reference explains that except E as N: behaves as if the block ended with del N, so the exception name is gone once the block finishes; assign it to another name inside the block if you need it later. And an explicit del name unbinds a local, so a later read fails the same way.

A related message, NameError: cannot access free variable 'y' where it is not associated with a value in enclosing scope, is the closure version: an inner function reads a variable of the outer function that was never bound before the inner one ran.

Stage 8

Catch the skipped path before it ships

pylint reports used-before-assignment (E0601) for reads that come before any binding and possibly-used-before-assignment (E0606) for names bound only under a condition. Running it in CI turns the GET-request crash into a review comment.

Only the two checks that matter here

python -m pip install pylint
python -m pylint app.py --disable=all --enable=used-before-assignment,possibly-used-before-assignment
  • After fixing, exercise the skipped path on purpose: a GET request, a mocked API failure, an empty list. The fix is confirmed when that path returns normally or raises your own clear error.

If you only keep one thing

  • One assignment anywhere makes the name local for the whole function.
  • Find the path that skips the assignment: if, try, for, except-as or del.
  • Bind a default before the block, or end the path with return or raise.
  • Use global or nonlocal only when changing the outer name is intended.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Next step

Want a second pair of eyes on it?

Send me the error and what changed before it started. I reply within 24 hours.