python
name_error
ai_generated
true
NameError: name 'variable' is not defined
ID: python/nameerror-not-defined
95%Fix Rate
95%Confidence
50Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 311 | active | — | — | — |
Root Cause
Variable or function referenced before assignment. Common after refactoring, conditional assignments, or typos.
genericWorkarounds
-
95% success Check for typos and ensure variable is assigned in all code paths
Check for typos and ensure variable is assigned in all code paths
Sources: https://docs.python.org/3/reference/executionmodel.html#naming-and-binding
-
90% success Move import or assignment before first use; check conditional branches all assign
# Ensure all branches assign the variable: if condition: result = compute() else: result = default_value # Don't leave this branch without assignment # Also check: is the import above this line?Sources: https://docs.python.org/3/tutorial/controlflow.html
Dead Ends
Common approaches that don't work:
-
Add global declaration
65% fail
Usually masks a scoping issue rather than fixing it
-
Initialize variable to None at module level
60% fail
Hides the real bug — the variable should come from specific logic
Error Chain
Frequently confused with: