Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

NameError — referencing an undefined name

NameError means Python could not find a referenced name in the available scopes. Check spelling, assignment order, and imports. Distinguish NameError from AttributeError. UnboundLocalError is a subclass of NameError.

Version: Python 3.14; repository image, production runtime not attested

Syntax

try:
    ...
except NameError as exc:
    ...

NameError occurs during execution when Python cannot find a referenced name in the available scopes. It applies to unqualified names such as total. If an object obj exists but has no attribute value, the failed reference obj.value normally raises AttributeError, not NameError.

Check spelling and whether the assignment or import binding the name executed before its use. Also check that the name is visible in the current scope. An assignment placed later in the file does not make its value available to code that executes earlier.

UnboundLocalError is a subclass of NameError: it occurs when a local variable in a function or method is read before a value has been bound to it. An assignment to a name anywhere in a function block can cause that name to be treated as local. Consequently, except NameError also catches UnboundLocalError.

In the example, ttoal is a misspelling of total. The handler prints the exception type and its name attribute, and the program then prints the correct value. Catching the exception does not retry the failed expression. In ordinary code, fix the cause rather than hiding the bug with broad exception handling.

Examples

total = 12
try:
    print(ttoal)
except NameError as exc:
    print(type(exc).__name__)
    print(exc.name)
print(total)

Result

NameError
ttoal
12

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources