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

Python throws NameError when you reference a name that does not exist in the current scope at the time of execution. The name could be a variable, function, class, or module.

Python looks up names in this order:

  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 is not found in any of these four places, you get NameError.

Pattern 1: Variable Used Before Assignment

python
def get_profile():
    print(user['name'])  # NameError: name 'user' is not defined
    user = fetch_user()

Python does not scan ahead. The variable must be assigned before the line that uses it.

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. Check spelling and case. Use your IDE's autocomplete — it only suggests names that exist in scope.

python
print(user_name)

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 does not exist in the outer scope after the function returns. Return the value instead:

python
def calculate():
    return 42

result = calculate()
print(result)

Note: If you need shared state, use a class or pass values as parameters. Global variables create hidden coupling and make bugs harder to trace.

Pattern 4: Module Used Without Import

python
path = os.path.join('home', 'user')  # NameError: name 'os' is not defined

Import the module at the top of the file:

python
import os

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

Common ones that get missed:

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'

    return status  # NameError if code is 500

Initialize with a default before the conditional so all paths are covered:

python
def get_status(code):
    status = 'unknown'

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

    return status

Finding the Error Fast

The stack trace always includes the file name and line number:

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

Go to line 23. Trace backward. Where was config supposed to be assigned? Was it inside an if block that did not run? Was it in a function that was never called? Was it in a different file that was not imported?

Tip: In VS Code, hover over any name before running the code. The editor flags unresolved names. Catches most NameError before execution.

Quick Diagnosis

Error messageFirst check
name 'x' is not definedIs x assigned above this line?
name 'pd' is not definedDid you run 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 without global

FAQ

Q: Why does NameError appear only sometimes when I run the code?

A: The name is probably inside a conditional branch that does not always run. Pattern 5 above covers this exactly. Add a default assignment before any conditional that sets the variable.

Q: Can I catch NameError with a 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 swallowing the error.


For NameError that appears only at runtime based on specific inputs, paste the function and the call stack into DebugAI and it will trace which conditional branch failed to assign the name.

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