Fixing Python NameError: Causes and Solutions
Understand why Python raises NameError, how to fix undefined variables, scope issues, and import errors, and how to prevent them in your code.

When Python raises NameError: name 'x' is not defined, it means the interpreter could not find a name in the current namespace. This error stops execution immediately, and its cause is often straightforward once you inspect the traceback. The most common triggers are typos, using a variable before it is assigned, scope boundaries, and missing imports. This article walks through each cause with concrete examples and shows how to resolve them systematically.
What Triggers Python NameError
Python resolves names at runtime by looking them up in the local, enclosing, global, and built-in scopes, in that order. If a name is not found in any of these, Python raises NameError. The error message includes the name that was not found, which is the first clue. For example:
def greet():
message = "Hello"
print(mesage) # typo: 'mesage' instead of 'message'
greet()This raises NameError: name 'mesage' is not defined. The traceback points to the exact line, so checking the spelling is usually the quickest fix. But not every NameError is a typo. Scope and import issues are just as common, especially in larger codebases.
Undefined Variables and Typos
The simplest cause is referencing a variable that was never assigned in the current scope. This can happen when a variable is conditionally defined, or when a name is misspelled. Consider this example:
count = 0
if some_condition:
count = 1
print(cout) # typoHere, cout is undefined regardless of some_condition. Python does not infer intent from similar names. The fix is to correct the spelling. In longer functions, typos are easy to miss, especially with names like user_id versus userid. A linter with static analysis, such as ruff or mypy, can catch undefined names before runtime.
Another common scenario is using a variable that is only defined inside a loop or conditional block. Python does not have block-level scope; variables assigned inside an if or for block are visible after the block ends, but only if the block executed. If the block did not run, the variable remains undefined.
def process(items):
if items:
first = items[0]
print(first) # UnboundLocalError if items is emptyThis is a runtime condition, not a syntax error. Inside process, Python treats first as a local variable because it is assigned somewhere in the function, so an empty items list raises UnboundLocalError, a subclass of NameError; at module level, the same pattern would raise a plain NameError. The fix is to initialize first before the conditional, or restructure the logic to avoid relying on a possibly unset variable.
Scope: Local, Global, and Nonlocal
Scope issues frequently produce NameError or its subclass UnboundLocalError, especially when a function assigns to a variable that also exists at module level. Python decides whether a variable is local based on assignment anywhere in the function. If you assign to a name inside a function, it is local to that function, even if the assignment appears after the reference.
value = 10
def show():
print(value) # UnboundLocalError, a NameError subclass
value = 5This raises UnboundLocalError, a subclass of NameError, because value is considered local due to the later assignment, and it is used before assignment. The message differs from a plain NameError, but the root cause is similar: the name is not yet bound. To fix this, either remove the local assignment or use the global keyword if you intend to modify the module-level variable.
value = 10
def show():
global value
print(value) # prints 10
value = 5For nested functions, nonlocal works similarly for variables in an enclosing function scope. The global declaration only controls where assignments are stored; it does not bind the name by itself. If missing is not assigned anywhere at module level, declaring global missing will not prevent a later reference from raising NameError. nonlocal is stricter: the name must already be bound in an enclosing function scope, otherwise Python raises a SyntaxError.
NameError from Missing Imports
A very common cause is using a module or symbol that was never imported. This often happens when you copy code from a snippet and forget the import line. For example:
import os
print(os.getcwd())
print(sys.version) # NameError: name 'sys' is not definedThe fix is to add import sys. The same applies to from imports: if you use from math import sqrt, then sqrt is available, but math itself is not. Referencing math.pi would raise NameError. This is a subtle trap when mixing import styles.
Another scenario is importing inside a function but using the name outside that function. Imports are local to the scope where they appear. If you need the name in multiple functions, import at module level.
def load_data():
import json
return json.loads('{"a": 1}')
print(json.dumps({"b": 2})) # NameError: name 'json' is not definedTo avoid this, move the import to the top of the file. In larger projects, circular imports can also cause NameError, where two modules import each other and a name is not yet defined when one module tries to use it. This is more complex and usually requires restructuring the imports.
Using Variables Before Assignment
Python evaluates the right-hand side of an assignment before binding the left-hand name. This means you cannot use a variable to compute its own new value unless it already exists. A classic mistake is:
total = total + 1 # NameError at module level if total was never definedAt module level, this raises a plain NameError. Inside a function, the assignment makes total local, so the same line raises UnboundLocalError unless total was initialized earlier in the function. The fix is to initialize total before the increment. In loops, forgetting to initialize an accumulator is a frequent cause.
def sum_values(numbers):
total = 0
for n in numbers:
total += n
return totalAnother edge case is using a variable in a default argument value. Defaults are evaluated at function definition time, so they must reference names that exist at that moment. If you reference a variable that is defined later in the module, you get NameError.
def add(x, y=default): # NameError: default not defined yet
return x + y
default = 5To fix this, use None as the default and assign inside the function, or define the default variable before the function.
Debugging NameError with Tracebacks
The traceback is your primary tool. It shows the exact file and line where the error occurred. The line itself often contains the problematic name, but sometimes the error is on a line with multiple operations. For example:
result = process(data) + offsetIf offset is undefined, the traceback points to this line. To isolate the issue, you can add print statements before the line to inspect which names are defined. In an interactive session, you can use dir() to list names in the current scope, or locals() and globals() to see the full namespace dictionaries.
For a more systematic approach, use a debugger like pdb to step through the code. Set a breakpoint before the failing line and examine the namespace. This is especially useful when the error occurs inside a complex function or a library call that you cannot easily modify.
A practical technique is to use traceback.print_exc() in a try block to capture the error, but the default traceback is usually sufficient. The key is to read the message carefully: it names the missing identifier. Then ask: where should this name be defined? Is it a local variable, a global, an import, or a built-in? This narrows the search.
Preventing NameError in Larger Codebases
NameError is a runtime error, so it can slip into production if tests do not cover the failing path. Static analysis tools catch many cases before execution. For example, mypy with --strict flags undefined names as errors, and ruff has rules for undefined names. Integrating these into your CI pipeline reduces the chance of NameError reaching users.
In addition, follow consistent naming conventions and avoid abbreviations that are easy to mistype. For example, use user_id consistently instead of userid in one place and user_id in another. When working with imports, prefer explicit imports over wildcard imports (from module import *) because wildcards can introduce names that are not obvious and may be missing if the module changes.
For variables that are conditionally defined, initialize them early with a sensible default. This makes the code more predictable and avoids NameError when a condition is false. For example:
def find_user(users, target_id):
result = None
for user in users:
if user.id == target_id:
result = user
break
return resultHere, result is always defined, even if no user matches. This pattern is clearer than relying on a variable that may or may not be assigned.
Finally, when refactoring code, be aware that moving assignments between scopes can introduce NameError. Use your editor's find-references feature to see all usages of a name before changing its scope. A NameError is often a symptom of a design issue, such as a variable that should be an argument or a return value. If a function needs data from outside, pass it as a parameter rather than relying on a global that may not exist in all contexts. This makes the dependency explicit and eliminates a whole class of NameError.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.