A Python NameError occurs when you reference a variable that doesn't exist in the current scope. It's one of the most common errors beginners face, and it's caused by simple typos, missing imports, or misunderstanding how Python's scoping rules work. If you've seen NameError: name 'X' is not defined, you're in the right place—this guide walks you through diagnosing and fixing undefined variable errors.
NameError undefined variable Python issues rarely crash your entire application in production, but they do cause unexpected behavior and make logs harder to read. The good news: they're trivial to fix once you know what to look for.
What is a NameError?
A NameError is raised whenever Python tries to evaluate a name (variable, function, class, or module) that doesn't exist in any accessible scope. Python looks for the name in the local scope first, then the enclosing scope, then global scope, and finally the built-ins module. If it can't find it anywhere, it raises:
NameError: name 'x' is not defined
The error message itself is helpful—it tells you exactly which name Python couldn't find. The challenge is figuring out why it doesn't exist.
Common Causes of NameError
Typos in Variable Names
The single most common cause is a simple typo. You defined user_name but referenced username. Python treats these as completely different names:
user_name = "Alice"
print(username) # NameError: name 'username' is not defined
Python is case-sensitive, so User_Name and user_name are different variables. If you swap capitalization, you'll get a NameError.
Missing or Incorrect Imports
If you try to use a module, class, or function without importing it first, Python won't find it:
data = json.loads('{"key": "value"}') # NameError: name 'json' is not defined
You need to add import json at the top. The same applies to specific imports:
users = [User(name="Alice"), User(name="Bob")] # NameError: name 'User' is not defined
If User is defined in another module, you must import it: from models import User.
Variables Defined in the Wrong Scope
Variables defined inside a function or block aren't visible outside of it. This is easy to miss:
def create_user(name):
user = {"name": name}
print(user) # NameError: name 'user' is not defined
The user dictionary only exists inside create_user(). Once the function returns, that variable is gone. To fix this, return the value: return user.
Conditional Definition Issues
If a variable is defined only inside an if block, it won't exist if that condition is never true:
if user_role == "admin":
permissions = ["read", "write", "delete"]
print(permissions) # NameError if user_role != "admin"
Always initialize variables before conditionally assigning to them:
permissions = []
if user_role == "admin":
permissions = ["read", "write", "delete"]
Debugging NameError
When you see a NameError, the stack trace tells you exactly where to look. How to read a stack trace is essential for understanding what went wrong. The traceback will show you the line number and the exact name that's missing.
Use your IDE's autocomplete and "go to definition" features aggressively. Modern editors like VS Code and PyCharm will catch many NameErrors before you run the code.
Print the variables you expect to exist to verify they're actually in scope:
def process_user(user_dict):
print(f"Variables in scope: {locals()}")
name = user_dict.get("name")
print(f"name = {name}")
return name.upper() # Check if name is None
If a variable is None, calling methods on it will raise a different error (AttributeError), but checking locals() helps you confirm what's actually available.
How to Fix NameError
Check Your Spelling First
Read the error message carefully. It tells you the exact name Python couldn't find. Search your code for that name and verify:
- Does it exist? (Is it defined anywhere?)
- Is the spelling and capitalization correct?
- Is it in scope where you're using it?
A quick find-and-replace (Ctrl+F) often reveals the typo immediately.
Verify All Imports
At the top of your file, list all modules and classes you use. If you reference something that's not in that list, add the import:
import json
from datetime import datetime
from models import User, Product
If you're using a function from a module in the standard library and forget the import, the fix is straightforward. For third-party modules, make sure they're installed (pip install module_name).
Use a linter like pylint or flake8 to catch undefined names before runtime. Most IDEs run these automatically and highlight errors as you type.
Watch Your Scope
If a variable is defined inside a function, don't expect it to exist outside. Instead, have the function return it or define it at the module level:
# Wrong: user only exists inside the function
def get_user():
user = {"name": "Alice"}
# Correct: return the variable
def get_user():
user = {"name": "Alice"}
return user
current_user = get_user()
print(current_user["name"])
For variables that need to persist across function calls, consider a class:
class UserSession:
def __init__(self):
self.user = None
def set_user(self, name):
self.user = {"name": name}
def get_user(self):
return self.user
session = UserSession()
session.set_user("Alice")
print(session.get_user())
Tracking NameError in Production
In development, NameError is easy to spot because your code doesn't run. In production, if a code path rarely executes or an import is conditional, NameError can slip through. That's where error tracking becomes invaluable.
When an unhandled NameError occurs in production, an error tracker like LightTrace captures the full stack trace, the state of local variables, and breadcrumbs leading up to the error. This lets you see exactly which users hit the error and under what conditions, making it much easier to reproduce and fix.
To use LightTrace with Python, install the Sentry SDK and point it at LightTrace:
import sentry_sdk
sentry_sdk.init(
dsn="https://<key>@light-trace.robomiri.com/1",
traces_sample_rate=1.0
)
# Your app code here
user = undefined_variable # Caught and sent to LightTrace
Every NameError is automatically grouped by the undefined name and stack frame. You can follow best practices for error tracking to ensure your team isn't overwhelmed with noise, and learn how to debug production errors systematically.
Never catch NameError with a bare except: clause to hide it. It's always a sign of a bug in your code. Fix the root cause instead of suppressing the error.
NameError is one of Python's clearest error messages. Take it at face value, search your code, check your imports, and verify scope—you'll find the issue in seconds. Use a linter and error tracking in production to catch them before users do.
Start tracking errors in minutes
Get real-time alerts for NameError and every other Python exception. Try LightTrace free today—no credit card required. Start free.