Skip to main content

How to Resolve Python "NameError: name '...' is not defined" (Common Cases)

The NameError: name '...' is not defined is one of Python's most fundamental errors. It occurs when you try to use a variable, function, class, or module that Python doesn't recognize in the current scope because it hasn't been defined, assigned a value, or imported correctly.

This guide covers common scenarios leading to NameError, focusing on forgetting to import standard library modules (like time, datetime, json, re, csv) and using keywords from other languages/formats (like null, true, false) instead of their Python equivalents (None, True, False).

Understanding the Error: Undefined Names

Python requires that any name (variable, function, class, module) must be defined or imported before it can be used. When the interpreter encounters a name it hasn't seen before in the current context (scope), it raises a NameError. This prevents typos from creating unintended variables and ensures that all code dependencies are explicitly stated.

Cause 1: Standard Library Module Not Imported

Many powerful features in Python reside in its standard library modules. Even though these modules ship with Python, they are not automatically loaded into your script's namespace. You must explicitly import them.

Examples: time, datetime, timedelta, re, csv, json

Forgetting the import statement is a very common cause of NameError.

# Error Scenario Examples (without imports)
try:
time.sleep(1) # ⛔️ NameError: name 'time' is not defined
except NameError as e: print(e)

try:
today = datetime.date.today() # ⛔️ NameError: name 'datetime' is not defined
except NameError as e: print(e)

try:
delta = timedelta(days=1) # ⛔️ NameError: name 'timedelta' is not defined
except NameError as e: print(e)

try:
match = re.search('a', 'abc') # ⛔️ NameError: name 're' is not defined
except NameError as e: print(e)

try:
# Assuming 'data.csv' exists
# with open('data.csv') as f:
# reader = csv.reader(f) # ⛔️ NameError: name 'csv' is not defined
pass
except NameError as e: print(f"CSV Example Error: {e}") # Would error if code run

try:
data_str = json.dumps({'a':1}) # ⛔️ NameError: name 'json' is not defined
except NameError as e: print(e)

try:
val = sleep(1) # ⛔️ NameError: name 'sleep' is not defined
except NameError as e: print(e)

Solution 1: Import the Entire Module (import module_name)

Import the required module(s) at the top of your file. Access functions, classes, or constants within the module using module_name. prefix.

# ✅ Import the required modules
import time
import datetime
import re
import csv
import json
import io # For csv example

# --- Using imported modules ---
print("Pausing...")
time.sleep(0.1) # Use time.
print("Done pausing.")

today = datetime.date.today() # Use datetime.
print(f"Today is: {today}")

pattern = r'\d+'
match = re.search(pattern, "Order 123") # Use re.
if match: print(f"Regex found: {match.group(0)}")

# Simulate CSV
csv_data = io.StringIO("id,value\n1,10\n2,20")
reader = csv.reader(csv_data) # Use csv.
print("CSV Data:")
for row in reader: print(row)

my_dict = {'status': 'ok'}
json_string = json.dumps(my_dict) # Use json.
print(f"JSON String: {json_string}")

Output:

Pausing...
Done pausing.
Today is: 2025-04-24
Regex found: 123
CSV Data:
['id', 'value']
['1', '10']
['2', '20']
JSON String: {"status": "ok"}

Import only the specific functions, classes, or constants you need directly into your script's namespace. This often makes code more readable and slightly less verbose as you don't need the module prefix.

# ✅ Import specific names
from time import sleep
from datetime import date, timedelta, datetime # Can import multiple
from re import search, compile
from csv import reader
from json import dumps, loads
import io

# --- Using imported names directly ---
print("Pausing again...")
sleep(0.1) # No prefix needed
print("Done pausing again.")

today = date.today() # No prefix needed
one_week = timedelta(weeks=1) # No prefix needed
print(f"Today: {today}, Next Week: {today + one_week}")

pattern = compile(r'\d+') # No prefix needed
match = search(pattern, "Ticket 456") # No prefix needed
if match: print(f"Regex found: {match.group(0)}")

csv_data = io.StringIO("id,value\n1,10\n2,20")
csv_reader = reader(csv_data) # No prefix needed
print("CSV Data (Specific Import):")
for row in csv_reader: print(row)

my_dict = {'status': 'ok'}
json_string = dumps(my_dict) # No prefix needed
print(f"JSON String: {json_string}")

Output:

Pausing again...
Done pausing again.
Today: 2025-04-24, Next Week: 2025-05-01
Regex found: 456
CSV Data (Specific Import):
['id', 'value']
['1', '10']
['2', '20']
JSON String: {"status": "ok"}

Pitfalls: Import Scope, Case Sensitivity, Filename Shadowing

  • Scope: Place import statements at the top level of your file, not inside functions or try...except blocks, to ensure names are available throughout the module.
  • Case Sensitivity: Module and function/class names are case-sensitive (import datetime, not import Datetime).
  • Filename Shadowing: Crucially, do not name your script files the same as standard library modules (e.g., time.py, json.py, re.py, csv.py, datetime.py). This causes Python to import your file instead of the intended module, leading to NameError or AttributeError. Rename your file if a conflict exists.

Cause 2: Using null, true, false Instead of None, True, False**

This error arises from using naming conventions common in other languages (like JavaScript, JSON, SQL) or data formats directly within Python code.

Python Keywords vs. Other Languages/Formats

  • Null/Absence of Value: Python uses None (capital 'N'). JSON, JavaScript, SQL use null.
  • Boolean Values: Python uses True and False (capital first letter). JSON, JavaScript use true and false.

Using null, true, or false directly in Python code results in a NameError.

Solution: Use None, True, False

Replace the lowercase versions with Python's capitalized keywords.

# Error Examples:
# value = null # ⛔️ NameError
# is_ready = true # ⛔️ NameError
# has_error = false # ⛔️ NameError

# ✅ Correct Python Keywords:
value = None
is_ready = True
has_error = False

print(value, is_ready, has_error) # Output: None True False

Handling JSON Data Containing null, true, false

A very common source of confusion is when you have a string containing JSON data. The null, true, and false within the JSON string are valid JSON, but not valid Python until parsed.

import json

json_string = r'{"name": null, "active": true, "isAdmin": false}'
print(f"JSON String: {json_string}")

# Incorrect: Trying to evaluate the string contents as Python code
# eval(json_string) # Raises NameError (and is insecure!)

# ✅ Correct: Parse the JSON string into a Python object
python_data = json.loads(json_string)
print(f"Parsed Python data: {python_data}")
# Output: Parsed Python data: {'name': None, 'active': True, 'isAdmin': False}

# Now access using Python keywords
print(f"Name from parsed data: {python_data['name']}") # Output: Name from parsed data: None
print(f"Is active: {python_data['active']}") # Output: Is active: True

Output:

JSON String: {"name": null, "active": true, "isAdmin": false}
Parsed Python data: {'name': None, 'active': True, 'isAdmin': False}
Name from parsed data: None
Is active: True
  • json.loads() correctly converts JSON null to Python None, JSON true to Python True, and JSON false to Python False.
  • Similarly, if using the requests library, response.json() handles this conversion automatically.

Discouraged Workaround: Assigning Keywords

Avoid assigning null = None, true = True, false = False. This makes code confusing and unpythonic. Fix the source by using the correct keywords or parsing JSON properly.

Debugging NameError

  1. Read the Error: The message NameError: name 'X' is not defined tells you exactly which name X Python doesn't recognize.
  2. Check Imports: If X is a module or something from a module, ensure the correct import X or from module import X statement exists before the line causing the error and is at the top level.
  3. Check Scope: If the import is inside a function, is the name being used outside that function? Move the import to the top level.
  4. Check Spelling and Case: Did you misspell the name or use incorrect capitalization (e.g., DateTime instead of datetime)?
  5. Check for Python Keywords: If X is null, true, or false, replace it with None, True, or False.
  6. Check for JSON Parsing: If the error involves null/true/false and the data originated as a string, ensure you're parsing it with json.loads() first.
  7. Check Filename: Make sure your script file isn't named the same as the module you are trying to import.

Conclusion

NameError: name '...' is not defined fundamentally means a name wasn't introduced into the current scope before being used.

Key solutions include:

  • Import Standard Library Modules: Always use import module_name or from module_name import name before using features from modules like time, datetime, re, json, csv, etc. Place imports at the top level.
  • Use Correct Python Keywords: Use None, True, and False (capitalized) instead of null, true, false.
  • Parse JSON Data: If data containing null, true, or false comes from a JSON string, use json.loads() to convert it into the corresponding Python objects (None, True, False) before using them in Python logic.
  • Check Spelling and Scope: Ensure correct spelling, capitalization, and that imports are accessible where needed.
  • Avoid Filename Conflicts: Do not name your files after standard library modules.

By correctly importing necessary modules and using Python's specific keywords, you can readily fix these common NameError exceptions.