Why does a function raise UnboundLocalError for a name that exists globally?
Quick answer
If a function assigns to a name anywhere in its body, Python treats that name as local throughout the function unless you declare it global or nonlocal. Reading it before assigning it locally can therefore raise UnboundLocalError, even when a global with the same name exists. [S1] Rename the local variable, pass the value in and return an updated value, or explicitly declare global when you intend to rebind the module-level name.
The question, the details, the next step.
A practical checklist
Find every assignment to the name inside the function, including augmented assignments such as
+=.Check whether the function reads that name before its local assignment.
If the function should calculate a result, pass in the value and return the result.
If rebinding an outer name is deliberate, choose
globalfor a module name ornonlocalfor an enclosing function binding.Run the smallest example that reproduces the error, then verify the chosen fix in the surrounding code.
A few more useful answers
Does assigning to the name later in the function make an earlier read use the global?
No. A binding anywhere in the function makes the name local throughout that function unless declared global or nonlocal, so an earlier read can raise UnboundLocalError. [S1]
Can `nonlocal` fix this when the value is defined at module level?
No. nonlocal refers to a previously bound name in an enclosing function scope, not a module global. Use global only if you intend to rebind the module-level name. [S1]
What is a simple alternative to changing a global inside a function?
Pass the current value as an argument, calculate a local result, and return it. The caller can decide whether to replace its existing value or keep the result separately.
Sources
References used for this guide.
- [S1] Python 3.14 Language Reference: Execution model — Naming and binding docs.python.org · Checked
