NameError

A bare name that Python cannot find in the local, enclosing, global or builtin scope — at the moment the line runs, not when the file is read.

InheritsBaseException›Exception›NameError
Lookup exceptionPython 3 (all)Live demo
NameError(*args, namename — Keyword-only. The name that was not found; set automatically by the interpreter (3.10+).type: str | None · default: None=None)
Raised by
reading an unassigned, misspelled, deleted or not-imported name
Message
name 'x' is not defined
Quick fix
fix the spelling, import it, or assign it on every path
Watch out
defined only inside an if/try/for body that did not run

Demo

Live evaluation
kind is only assigned when the if body runs. Names are looked up when the line executes, so the error depends on the value.
Try:
Inputs
ninttry 0 or a negative
Code
if 5 > 0:
    kind = 'positive'
kind
Result
'positive'

The file is valid either way — Python only notices the missing name when the line kind actually runs. With 0 or a negative number the if body is skipped, so kind was never bound. Catching NameError works (Handle), but the real fix is to give the name a value before the if: kind = 'non-positive'.

Constructor

NameTypeRequiredDescription
*argsobjectnoUsually one message string. str(e) is that message.
namestr | Noneno (None)Keyword-only. The name that was not found; set automatically by the interpreter (3.10+).

Attributes

AttributeTypeMeaning
namestr | NoneThe name that was not found (3.10+). None for a NameError you construct without name=, and for UnboundLocalError.
argstupleThe constructor arguments; args[0] is the message, e.g. "name 'x' is not defined".

Common patterns

Assign before branching
Give the name a value that covers the path where no branch runs.
kind = 'unknown'
if n > 0:
    kind = 'positive'
elif n < 0:
    kind = 'negative'
Optional dependency
Bind the name either way, so later code can test it instead of hitting NameError.
try:
    import numpy as np
except ImportError:
    np = None
Define before calling at module level
Functions can refer to names defined later in the file, but module-level code runs top to bottom — call main() last.
def main():
    return helper()

def helper():
    return 'ok'

if __name__ == '__main__':
    main()

Examples

1. Typo in a builtin
prnt('hi')
Returns
NameError: name 'prnt' is not defined. Did you mean: 'print'?
2. Module used but not imported
math.sqrt(4)
Returns
NameError: name 'math' is not defined. Did you forget to import 'math'?
3. JSON / JavaScript literal
true
Returns
NameError: name 'true' is not defined. Did you mean: 'True'?
4. Assigned only on one path
try: x = int('oops') except ValueError: pass x
Returns
NameError: name 'x' is not defined
5. Loop that never ran
for i in range(0): last = i last
Returns
NameError: name 'last' is not defined. Did you mean: 'list'?
6. Local to a function
def f(): total = 0 return total f() total
Returns
NameError: name 'total' is not defined
7. After del
x = 1 del x x
Returns
NameError: name 'x' is not defined
8. e.name holds the missing name
try: undefined_thing except NameError as e: r = e.name r
Returns
'undefined_thing'

Pitfalls

1. Calling a function before its def runs
def is an executable statement. At module level, a call placed above the def fails because the name is not bound yet.
Call above def
result = helper()
def helper():
    return 'ok'
NameError: name 'helper' is not defined. Did you mean: 'help'?
Call after def
def helper():
    return 'ok'
result = helper()
result
'ok'
2. Class attributes are not in scope inside methods
The class body is not an enclosing scope for its methods. Reach class attributes through self or the class.
bare x
class A:
    x = 1
    def get(self):
        return x
A().get()
NameError: name 'x' is not defined. Did you mean: 'self.x'?
self.x
class A:
    x = 1
    def get(self):
        return self.x
A().get()
1
3. Class attributes in a comprehension
Same rule inside a class body: a comprehension there cannot see the class-level names (except the first iterable).
x in the expression
class A:
    x = 2
    y = [x * i for i in range(3)]
A.y
NameError: name 'x' is not defined
Loop over x instead
class A:
    x = 2
    y = [x * i for x in [x] for i in range(3)]
A.y
[0, 2, 4]

When to use

Use it
  • Catching it is rare — it almost always signals a bug to fix, not handle
  • Probing for an optional name in generated or exec() code
  • Tests asserting that a name is deliberately not exported
Reach for something else
  • Optional imports → bind the name to None in except ImportError
  • Maybe-assigned variables → initialise before the if/try/for
  • Dynamic variable names → use a dict instead of globals()

Notes

Did you mean
3.10+: the traceback printer searches the failing frame's locals, globals and builtins (and self's attributes inside a method, 3.12+) for a close match. The output boxes on this page show that traceback line, so they include it; str(e) and e.args never do.
Forgot to import
3.12+: for a standard-library module name (sys.stdlib_module_names) the traceback adds . Did you forget to import 'math'? — it needs no frame, so format_exception_only shows it too; str(e) never does
Subclass
UnboundLocalError is a NameError subclass for locals read before assignment
Scope order
Local → enclosing function → global (module) → builtins (LEGB)

FAQ

Python looked for that bare name in the local, enclosing, global and builtin scopes and found nothing at the moment the line ran. The usual causes: a typo (prnt), a missing import (math.sqrt without import math), a variable assigned only inside an if, try or for body that did not run, a name local to another function, or a JavaScript/JSON literal (true, null instead of True, None).

History

3.10
Added the name attribute.