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.
Trace a failed name lookup through local, enclosing, global, and built-in scopes before diagnosing NameError. section 10.4.1
