Python Error Guide: 'NameError: name is not defined' — Cause, Fix, and Troubleshooting Guide
Fix Python 'NameError: name is not defined': fix typos, add missing imports, define before use, and understand scope so names resolve correctly.
- #python
- #automation
- #troubleshooting
- #errors
Stuck on this Bash & Python Automation error? Get the free incident triage checklist
A one-page PDF — the exact steps to isolate, fix, and verify a production error like this one. No spam, unsubscribe anytime.
Overview
Python raises NameError when it evaluates a name that isn’t bound in any reachable scope:
NameError: name 'reqeusts' is not defined
At the moment that line runs, Python looked for the name in the local, enclosing, global, and built-in scopes (the LEGB rule) and found nothing. The usual causes are a typo, a missing import, using a variable before it’s assigned, or referring to something defined in a different scope. Unlike SyntaxError, this happens at runtime, so the code up to that point did execute.
Symptoms
- The traceback ends in
NameError: name '<something>' is not definedat a specific line. - The name is a near-miss spelling of a real one (
reqeustsforrequests,FlaseforFalse). - A module name is undefined because its
importis missing or misspelled. - A variable defined inside a function or
ifbranch is referenced outside it.
Common Root Causes
- Typo in a variable, function, or module name (including wrong casing — Python is case-sensitive).
- Missing import — using
requests,json,Pathwithoutimport requests/from pathlib import Path. - Use before assignment — referencing a variable earlier than the line that defines it, or in a branch that didn’t run.
- Wrong scope — a name defined inside a function isn’t visible at module level (and vice versa without
global/nonlocal). - Deleted or never-created name — relying on a variable that only exists in another code path.
- Interactive/REPL state loss — a name defined in a previous session that no longer exists.
Diagnostic Workflow
Read the exact name in the message and compare against definitions:
grep -n "requests" script.py # is it imported? spelled consistently?
Confirm the import line exists and matches usage:
grep -nE "^import |^from " script.py
Lint the whole file — Pyflakes/Ruff report undefined names and unused imports before you run:
python3 -m pyflakes script.py # or: ruff check script.py
Example Root Cause Analysis
A small HTTP check failed at runtime:
resp = requests.get(url, timeout=5)
NameError: name 'requests' is not defined
The library was installed, but the file never imported it — the top of the script jumped straight into logic. python3 -m pyflakes flagged it immediately:
script.py:4: undefined name 'requests'
The fix is the missing import:
import requests
resp = requests.get(url, timeout=5)
A close relative is the typo case — reqeusts.get(...) — where the import is present but the use is misspelled. Either way, the name that Python couldn’t resolve is printed verbatim in the message; matching it against your imports and definitions points straight at the fix.
Prevention Best Practices
- Lint in a pre-commit hook — Pyflakes/Ruff catch undefined names and missing imports before code runs.
- Import at the top of the file and keep imports grouped so missing ones are obvious.
- Let your editor autocomplete names and imports to avoid typos.
- Define before use — assign variables above the point they’re referenced, and don’t rely on names set only inside conditional branches.
- Understand scope (LEGB) — return values out of functions rather than expecting locals to leak to module scope.
- Use a type checker (mypy/Pyright) which also surfaces unresolved names across modules.
Quick Command Reference
python3 -m pyflakes script.py # report undefined names + unused imports
ruff check script.py # fast lint, catches NameError sources
grep -nE "^import |^from " script.py # verify the import exists
grep -n "name" script.py # find every use of the reported name
python3 -c "import requests" # confirm the module is importable at all
Related Guides
- Python Error Guide: ‘ModuleNotFoundError: No module named’ — when the import itself fails because the package isn’t installed.
- Python Error Guide: ‘UnboundLocalError: local variable referenced before assignment’ — the scope-specific cousin of NameError inside functions.
- Python Error Guide: ‘SyntaxError: invalid syntax’ — the compile-time errors that stop code before NameError can occur.
Conclusion
NameError: name is not defined is a runtime lookup miss — Python evaluated a name that isn’t bound anywhere reachable. The printed name is your clue: check it for a typo, a missing import, use-before-assignment, or a scope mismatch. Lint with Pyflakes or Ruff in a pre-commit hook and most NameErrors are caught before the script ever runs. When it’s a scope issue inside a function, its close cousin UnboundLocalError is worth knowing too.
Fixed it? Get 500 Bash & Python Automation & DevOps AI prompts — free
500 battle-tested, copy-paste AI prompts engineered by a senior systems engineer — every one with fill-in placeholders and safety/back-out notes. Drop your email and it's yours.
- 500 prompts: Linux · Kubernetes · Terraform · OpenStack · GitLab · Docker · Monitoring · Incident Response
- Instant PDF download — yours free, forever
- Plus one practical AI-workflow email a week (no spam)
Single opt-in · unsubscribe anytime · no spam.
Did this fix your issue?
Get 500 Battle-Tested DevOps AI Prompts — Free
500 battle-tested, copy-paste AI prompts engineered by a senior systems engineer — every one with fill-in placeholders and safety/back-out notes. Drop your email and it's yours.
- 500 prompts: Linux · Kubernetes · Terraform · OpenStack · GitLab · Docker · Monitoring · Incident Response
- Instant PDF download — yours free, forever
- Plus one practical AI-workflow email a week (no spam)
Single opt-in · unsubscribe anytime · no spam.