NameError name is not defined
suggest changeA NameError is raised when you try to use a variable, method, or function that has not been defined yet. In other words, it is raised when a requested local or global name is not found. It’s possible that you misspelt the name of the object or forgot to import something. Also maybe it’s in another scope. We’ll cover those with separate examples.
It’s simply not defined anywhere in the code
It’s possible that you forgot to initialize it, especially if it is a constant
foo # This variable is not defined
bar() # This function is not defined
Maybe it’s defined later:
baz()
def baz():
pass
Or it wasn’t imported:
#needs import math
def sqrt():
x = float(input("Value: "))
return math.sqrt(x)
Defining sqrt does not look up math. The NameError is raised when sqrt() runs.
Python scopes and the LEGB Rule:
The so-called LEGB Rule talks about the Python scopes. Its name is based on the different scopes, ordered by the corresponding priorities:
Local → Enclosing → Global → Built-in.
- Local: Variables assigned in a function and not declared
globalornonlocal. - Enclosing: Variables defined in a function that is wrapped inside another function.
- Global: Variables declared global, or assigned at the top-level of a file.
- Built-in: Variables preassigned in the built-in names module.
As an example:
for i in range(4):
d = i * 2
print(d)
d is accessible because the for loop does not mark a new scope, but if it did, we would have an error and its behavior would be similar to:
def noaccess():
for i in range(4):
d = i * 2
noaccess()
print(d)
Python says NameError: name 'd' is not defined