CKTIS / Python
UnboundLocalError — reading an unbound local variable
UnboundLocalError occurs when a function reads a local variable that has no value bound to it at that point. It is a subclass of NameError; a common cause is an assignment that shadows a variable from an outer scope.
Version: Python 3.14; repository image, production runtime not attested
Syntax
UnboundLocalErrorUnboundLocalError means an attempt to read a function-local variable that is not bound to a value at that point. It is a subclass of NameError: a name that cannot be found causes NameError, whereas this specific case of an unbound local variable causes UnboundLocalError.
Assignment to a name inside a function makes it local throughout that function body unless a global or nonlocal declaration applies. This includes assignment in a branch that never runs. In the example, count += 1 must first read the local count; it does not use the module-level count = 10. The exception interrupts the call, and the module-level value remains 10.
Fix the cause: ensure a value is assigned before every possible read, or pass the value as an argument and return the result. If you intend to rebind a module-level name, use global; for an existing binding in the nearest enclosing function, use nonlocal. Place the declaration before using the name. Catching the exception in the example is for demonstration, not a repair for the scope error.
Examples
count = 10
def increment():
count += 1
return count
try:
increment()
except UnboundLocalError as error:
print(type(error).__name__)
print(count)
Result
UnboundLocalError 10
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.