NameError: name is not defined in Python
This error occurs when accessing an identifier before it has been defined or assigned. Initialize variables before conditional branches and check for spelling errors.
Root Cause Analysis
This error occurs when Python tries to evaluate an identifier or variable name that has not been bound in the local, enclosing, global, or built-in scope.
Cause 1: Conditional Assignment Without Fallback
When a variable is declared inside an if block that evaluates to False, the variable is never created in memory. Attempting to access that variable after the conditional block raises NameError: name 'auth_token' is not defined.
Cause 2: Typos and Case Sensitivity in Variable Names
Python variable names are case-sensitive and whitespace-sensitive. Declaring total_count = 10 and later referencing total_Count or totalcount triggers a NameError.
Cause 3: Scoping Rules (Local vs Global Scope)
Variables declared inside a function body belong strictly to the local function scope. Referencing a local variable outside its parent function fails because outer scopes cannot look inside function frames.
Cause 4: Missing Library Imports
Referencing a module or function (such as math.sqrt() or datetime.now()) without explicitly importing it beforehand causes Python to look for the identifier in local scope and fail.
Reproduction Code (MCVE)
status_flag = False
if status_flag:
auth_token = 'token_xyz'
print(auth_token)
Solution 1: Initialize Variables with Explicit Default Values Before Branching
Define variables with a clear sentinel value (like None or an empty container) before entering conditional branches so the identifier always exists in scope.
status_flag = False
auth_token = None
if status_flag:
auth_token = 'token_xyz'
print(f'Auth token: {auth_token}')
Solution 2: Provide an Explicit Else Fallback Branch
Ensure all execution paths through branching logic assign a value to the target variable.
status_flag = False
if status_flag:
auth_token = 'token_xyz'
else:
auth_token = 'anonymous_token'
print(f'Assigned token: {auth_token}')
Common Mistakes & Edge Cases
1. Contrasting NameError vs UnboundLocalError
NameError: The identifier does not exist in any accessible scope (local, enclosing, global, built-in).UnboundLocalError: A specialized subclass ofNameErrorthat occurs when a function assigns to a variable anywhere in its body (marking it local), but references it before that assignment takes place.
2. Forward References in Script Files
In Python scripts, functions and variables must be defined before they are called. Calling run_task() at the top of a file before def run_task(): is defined raises NameError.
3. Shadowing Built-In Names
Avoid naming variables list, dict, str, or id. While this does not raise NameError immediately, it shadows built-in constructors and leads to subtle runtime bugs later.