On this page

Engineering6 min read

Fix NameError in Python: "name 'X' is not defined", 6 Causes and Fixes

Python NameError means the interpreter hit a name it does not recognize. Here are the 6 most common causes: typos, scope, missing imports, and the exact fix for each one.

PythonNameErrordebuggingerror fixVS Code

What Is a NameError?

Python raises NameError when it encounters a name, whether a variable, function, or class, that has not been defined in the current scope.

Error: NameError: name 'user_data' is not defined

This error always means one of six things. Work through each cause below in order. Most NameErrors are fixed by cause 1 or 2.

Cause 1: Typo in Variable Name

Python is case-sensitive. UserData, user_data, and userdata are three different names. A single character difference causes NameError.

python
# Defined as user_data, referenced as userdata
user_data = fetch_user(user_id)
print(userdata['email'])  # NameError: name 'userdata' is not defined

Fix: Use your editor's "Go to Definition" (F12 in VS Code) on the erroring name. If it cannot navigate, the name does not exist. Check spelling against where it was defined.

python
user_data = fetch_user(user_id)
print(user_data['email'])

Cause 2: Variable Used Before Assignment

Python executes top to bottom. Referencing a variable before the line that assigns it causes NameError.

python
def calculate_total(items):
    print(f"Total: {result}")  # NameError here
    result = sum(item['price'] for item in items)
    return result

Move the reference after the assignment, or initialize the variable at the top of the function:

python
def calculate_total(items):
    result = sum(item['price'] for item in items)
    print(f"Total: {result}")
    return result

Cause 3: Variable Defined Inside a Conditional That Did Not Run

Variables assigned inside if blocks only exist if that branch executed. Referencing them outside is NameError waiting to happen.

python
def get_username(user_id):
    if user_id:
        user = api.get_user(user_id)
    return user.name  # NameError if user_id was falsy

Initialize the variable before the conditional with a sensible default:

python
def get_username(user_id):
    user = None
    if user_id:
        user = api.get_user(user_id)
    return user.name if user else 'Anonymous'

Cause 4: Scope Error — Variable Defined in a Different Function

Variables defined inside a function are local to that function. They do not exist in other functions or at module level.

python
def setup():
    config = load_config()

def run():
    print(config['debug'])  # NameError: config is not defined

setup()
run()

Return the value and pass it where needed:

python
def setup():
    return load_config()

def run(config):
    print(config['debug'])

config = setup()
run(config)

Note: Using global to fix scope issues is a code smell. If you find yourself reaching for global, the function design needs refactoring, not a global variable.

Cause 5: Missing Import

Built-in modules and third-party packages must be imported before use. Referencing them without importing raises NameError, not ImportError.

python
def get_timestamp():
    return datetime.now().isoformat()  # NameError: name 'datetime' is not defined

Add the import at the top of the file:

python
from datetime import datetime

def get_timestamp():
    return datetime.now().isoformat()

Tip: VS Code with Pylance auto-detects missing imports. Hover over the red underline, click "Quick Fix", then "Add import". Faster than typing it manually.

Cause 6: Name Defined in a Try Block, Used After

When an exception occurs inside a try block, any assignment after the error point does not happen. Code after the try/except can reference a name that was never set.

python
try:
    connection = db.connect(DATABASE_URL)
    cursor = connection.cursor()
except Exception as e:
    print(f"DB error: {e}")

cursor.execute("SELECT * FROM users")  # NameError if connect() failed

Move usage inside the try block where the name is guaranteed to exist:

python
try:
    connection = db.connect(DATABASE_URL)
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM users")
    return cursor.fetchall()
except Exception as e:
    print(f"DB error: {e}")
    return []

How to Find It Fast

Python's NameError stack trace points to the exact line. Read it bottom-up:

Traceback (most recent call last):
  File "app.py", line 47, in process_order
    total = calculate_discount(subtotal, promo_cide)
NameError: name 'promo_cide' is not defined. Did you mean: 'promo_code'?

Python 3.10+ includes "Did you mean?" suggestions. If you see that, it is a typo (Cause 1). Fix the name and move on.

Quick Reference

CauseSymptomFix
TypoName looks almost rightCheck spelling and case sensitivity
Used before assignedError on first referenceMove reference after assignment
Conditional scopeError only on some inputsInitialize before the if block
Function scopeError referencing another function's variableReturn and pass as argument
Missing importStandard library or package nameAdd import at file top
Try block scopeError after try/exceptMove usage inside try

FAQ

Q: Why does Python not catch NameError before running the code?

A: Python only resolves names at runtime, not at parse time. The exception fires when execution reaches that line. Enable Pylance strict mode in VS Code with "python.analysis.typeCheckingMode": "strict" to catch undefined names before you run the code.

Q: Can I catch NameError with try/except?

A: You can, but you should not. NameError almost always means a bug in the code, not a runtime condition to handle. Fix the root cause instead of catching it.


For cross-file or cross-scope NameErrors, paste the error and the surrounding function into DebugAI. It reads your imports, your function definitions, and your call sites, then identifies whether the name was never defined, defined in the wrong scope, or imported incorrectly.

Debug faster starting today.

Free VS Code extension. 10 sessions/day. No credit card.

Install Free →

Related Posts

Engineering

GitHub Copilot Just Changed Its Pricing. What Developers Need to Know

5 min read

Engineering

Why Your AI Agent Harness Fails at Debugging (And How to Fix It)

5 min read

← All posts