Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between NameError and AttributeError in Python?

What is the diffference between those 2 types of errors? When to use each one of them?

like image 302
Ababneh A Avatar asked Sep 06 '25 01:09

Ababneh A


2 Answers

Attributes are properties of functions or classes or modules, and if a property is not found then it raises attribute error.

NameError are related to variables.

>>> x=2
>>> y=3
>>> z    #z is not defined so NameError

Traceback (most recent call last):
  File "<pyshell#136>", line 1, in <module>
    z
NameError: name 'z' is not defined

>>> def f():pass

>>> f.x=2 #define an attribue of f
>>> f.x
2
>>> f.y   #f has no attribute named y

Traceback (most recent call last):
  File "<pyshell#141>", line 1, in <module>
    f.y
AttributeError: 'function' object has no attribute 'y'

>>> import math   #a module  

>>> math.sin(90) #sin() is an attribute of math
0.8939966636005579

>>> math.cosx(90)  #but cosx() is not an attribute of math

Traceback (most recent call last):
  File "<pyshell#145>", line 1, in <module>
    math.cosx(90)
AttributeError: 'module' object has no attribute 'cosx'
like image 140
Ashwini Chaudhary Avatar answered Sep 08 '25 23:09

Ashwini Chaudhary


From the docs I think the text is pretty self explanatory.

NameError Raised when a local or global name is not found. This applies only to unqualified names. The associated value is an error message that includes the name that could not be found.

AttributeError Raised when an attribute reference (see Attribute references) or assignment fails. (When an object does not support attribute references or attribute assignments at all, TypeError is raised.)

In you example above the reference to z raises NameError as you are trying to access an unqualified name (either local or global)

In you last example math.cosx is a dotted access (attribute reference) in this case is an attribute of the math module and thus AttributeError is raised.

like image 27
Tim Hoffman Avatar answered Sep 08 '25 21:09

Tim Hoffman