Python Glossary Русский

all Python 3Exceptionsexception

UnboundLocalError

built-in exceptions

Reading a local variable before it was assigned (a subclass of NameError).

Syntax

raise UnboundLocalError

Python decides local-or-not for the whole function body at once: if a name is assigned anywhere inside, it is local everywhere, so reading it before that line fails even when a global of the same name exists. count += 1 and total = total + 1 are the classic traps — the right-hand side reads a local that has not been created yet. If you really must modify the outer variable, declare global (or nonlocal inside a nested function), though passing it in as an argument and returning the result is usually cleaner.

Examples

try:
    raise UnboundLocalError
except UnboundLocalError as e:
    print(type(e).__name__)   # → UnboundLocalError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy