I have a Python NameError
exception, for example:
>>> def test():
... var = 123
...
>>> test()
>>> print(var)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'var' is not defined
What are the steps should I take to debug it? How do I fix it?
Read the NameError
exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'var' is not defined
The last line contains the name of the variable, in this case var
. Make sure the spelling is correct and you made no mistake.
Right above the NameError
, you can see the file name and the line number. This is the location where you tried to use the variable.
Look for a var =
or any function which contains var
as the argument:
def func(var):
...
Where is the variable you're trying to use? Where does it exist?
Try finding that name in all of your Python files using ctrl+f
in Windows or cmd+f
in Mac.
Am I in the same function?
def test():
var = 1
print(var) # This will not work.
def test2():
print(var) # This will not work either.
If you're not in the same function, try fixing by returning the variable:
def test():
var = 1
return var
var = test()
print(var) # This will work
or by accepting the variable as an argument:
var = test()
def test2(x): # var is now named 'x'
print(x)
test2(var)
You can also return multiple variables:
def test():
var1 = "hello"
var2 = "world"
return var1, var2
var1, var2 = test()
print(var1, var2) # Prints hello world.
If you are in the same function or using a global
, did you use if
statements and never entered them? Maybe an exception was thrown and you suppressed?
def test():
if False: # Never true
var = 123
print(var) # This will not work
def test2():
try:
2/0 # Throws an error
var = 123
except:
pass
print (var) # This will not work
class Test:
var = 123
def func(self):
print(var) # This will not work
Make sure you use self
to access it:
class Test:
var = 123
def func(self):
print(self.var) # This will work
pass it using a default parameter:
class Test:
var = 123
def func(self, param=var):
print(param)
or access it using the instance:
class Test:
var = 123
def func(self, param=var):
print(param)
inst = Test()
inst.var # This will work
inst.func() # This will work
Make sure you define before using it:
func()
def func(): # This will not work
pass
Are you trying to import it and forgot?
import operator
itemgetter # This will not work
operator.itemgetter # This will work
Are you sure you spelled it correctly? Remember, Python is case-sensitive!
For more information about scoping, see this answer.
If everything failed and you still haven't found your answer, you're always welcome to open a question and ask, or write in the comments of your existing stackoverflow question.
Read the question checklist an provide a minimal example - make sure your example contains enough code to see the location where the variable is defined, and where it is used, but not too much code as it will be hard to understand.