On this page

Engineering5 min read

Fix Python NameError: name 'x' is not defined — 5 Patterns and Fixes

Python NameError means a variable, function, or module doesn't exist in the current scope when Python tries to use it. Here are the 5 patterns that cause almost every NameError — with exact fixes and code examples for each.

pythonnameerrordebuggingscopevariables

What NameError Actually Means

Python throws NameError when you reference a name — variable, function, class, or module — that doesn't exist in the current scope at the time of execution.

Python's name lookup order (LEGB):

  1. Local scope (inside the current function)
  2. Enclosing scope (outer functions, for closures)
  3. Global scope (module level)
  4. Built-ins (len, print, range, etc.)

If the name isn't found in any of these four places, you get NameError.

Pattern 1: Variable Used Before Assignment

python
# ❌ Using user before it's defined
def get_profile():
    print(user['name'])  # NameError: name 'user' is not defined
    user = fetch_user()

Python doesn't scan ahead. The variable must be assigned before the line that uses it.

Fix: Move assignment above usage.

python
def get_profile():
    user = fetch_user()
    print(user['name'])  # ✅

Pattern 2: Typo in Variable or Function Name

python
user_name = "Alice"
print(userName)   # NameError: name 'userName' is not defined

Python is case-sensitive. userName, user_name, and username are three different names.

Fix: Check spelling and case. Use your IDE's autocomplete — it only suggests names that exist in scope.

python
print(user_name)  # ✅ matches assignment

Pattern 3: Variable Defined in Wrong Scope

python
def calculate():
    result = 42

calculate()
print(result)  # NameError: name 'result' is not defined

result is local to calculate(). It doesn't exist in the outer scope after the function returns.

Fix: Return the value.

python
def calculate():
    return 42

result = calculate()
print(result)  # ✅

Note: If you need genuinely shared state, use a class or pass as a parameter — not global. Global variables create hidden coupling and make bugs harder to trace.

Pattern 4: Module Used Without Import

python
# ❌ Using os without importing it
path = os.path.join('home', 'user')  # NameError: name 'os' is not defined

Fix: Import the module at the top of the file.

python
import os

path = os.path.join('home', 'user')  # ✅

Common ones you might forget:

python
import os
import sys
import json
import re
from datetime import datetime
from pathlib import Path

Pattern 5: Conditional Assignment Not Covering All Paths

python
def get_status(code):
    if code == 200:
        status = 'ok'
    elif code == 404:
        status = 'not found'
    # code == 500: status never assigned

    return status  # NameError if code is 500

Fix: Initialize with a default before the conditional.

python
def get_status(code):
    status = 'unknown'  # default covers all paths

    if code == 200:
        status = 'ok'
    elif code == 404:
        status = 'not found'

    return status  # ✅ always defined

Finding the Error Fast

Stack trace always includes file name and line number:

NameError: name 'config' is not defined
  File "app.py", line 23, in start_server
    host = config['host']

Go to app.py line 23. Trace backward — where was config supposed to be assigned? Was it inside an if block that didn't run? Was it in a function that wasn't called? Was it in a different file that wasn't imported?

Tip: In VS Code, hover over any name before running the code. The editor shows if the name is unresolved (undefined). Catches most NameError before execution.

Quick Diagnosis Table

Error messageFirst check
name 'x' is not definedIs x assigned above this line?
name 'pd' is not definedDid you import pandas as pd?
name 'X' is not defined (capital)Check case — Python is case-sensitive
free variable 'x' referenced before assignment in enclosing scopeClosure scope issue — restructure, don't use global

For NameError that appears only at runtime based on specific inputs (conditional paths that rarely execute), paste the function and the call stack into DebugAI. It traces which conditional branch failed to assign the name and shows the path that triggered the error.

Debug faster starting today.

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

Install Free →

Related Posts

Engineering

Fix Express CORS Error — No 'Access-Control-Allow-Origin' Header

6 min read

Engineering

Fix Django IntegrityError — UNIQUE, NOT NULL, and Foreign Key Violations

5 min read

← All posts