liveBook · Manning

NameError

As explained in Python How-To

NameError is the Python exception raised when a referenced name cannot be found in the applicable namespaces.

NameError is raised when Python cannot resolve a referenced name in any applicable namespace. Name lookup follows the LEGB order: local, enclosing, global, and built-in scopes. If every lookup fails, Python raises NameError. section 10.4.1

Use NameError diagnostics to distinguish an undefined name from other failures:

  • Check whether the referenced variable, function, or class was defined before use and is available in the expected scope. section 10.4.1
  • Catch NameError explicitly only when the failure is a known, meaningful case; avoid a bare except clause that hides unrelated errors. section 12.3.2
  • Use separate except clauses for unrelated exceptions, or group them when the same response is appropriate. section 12.3.3
  • Fix accidental undefined names in the code rather than relying on exception handling to conceal maintainability problems. section 12.3.3

Handling an undefined name

def process_task_string4(text): title, urgency_str = text.split(",") try: urgency = int(urgency_str) pending_task.urgency = urgency except ValueError: print("Couldn't cast the number") return None except NameError: print("You're referencing an undefined name") return None task = Task(title, urgency) return task process_task_string4("Laundry,3") # output: You're referencing an undefined name section 12.3.3

Figure 10.8 The general process of resolving a variable: the LEGB rule. When Python encounters a variable, it tries to resolve it by looking up the local, enclosing (if applicable), global, and built-in scopes sequentially. If the variable is resolved, Python uses the value; otherwise, it raises a NameError.
CH10_F08_Cui

Trace a failed name lookup through local, enclosing, global, and built-in scopes before diagnosing NameError. section 10.4.1

How Python How-To covers it

How deep it goes
Explains the exception definition, LEGB lookup, worked handlers, and maintainability implications without descending into interpreter internals.
Examples
Demonstrates an undefined pending_task, separate handlers, grouped exceptions, and contrasting ValueError inputs.
What it assumes
Assumes basic Python variables and exceptions while developing namespace lookup from the local scope upward.
What you can do after
Diagnose/debug with it: trace unresolved names through LEGB scopes and write targeted handlers for known failures.
How it connects
Connects NameError with namespaces, the LEGB rule, try-except statements, ValueError, and built-in exception classes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.