How to handle an attribute error in Python

An attribute in Python consists of the data variables and methods that are used to store the data and the functionalities respectively in an object.

An attribute error occurs when the Python interpreter is not able to find the particular attribute in the object asked, i.e you make an invalid attribute reference by accessing the value of the attribute or assigning an attribute value to a Python object that does not possess that attribute. A very simple and basic example of this is

class product:
    def __init__(self): 
        self.brand = 'abc'
        self.price = 2000
p=product()
print(p.discount)

Output:

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    print(p.discount)
AttributeError: product instance has no attribute 'discount'

In the above example, as the class product had no attribute named discount, the interpreter raised an Attribute Error.

Use the following steps to remove any Attribute Error in Python

Below are the steps to handle Python attribute error:

  • Check through your code to avoid any logical errors, also Python is a case sensitive language and a misspelled attribute can cause an attribute error.
  • You can check for any particular attribute if present inside an object using the Python in-built function hasattr().
  • You can list all the attributes of an object by using the in-built functions:
            1.  vars(): Displays all the attributes present in the instance in the form of a dictionary.
            2.  dir(): Displays the class attributes along with the object and instance attributes.
    These functions help to list all the attributes present in the particular object or class and help to avoid the Attribute Error to occur.

    An example to show the working of both the functions is given below:

    class product:
        def __init__(self): 
            self.brand = 'abc'
            self.price = 2000
    p=product()
    print('Using the function vars:')
    print vars(p)
    print('Using the function dir:')
    print dir(p)

    Output

    Using the function vars:
    {'brand': 'abc', 'price': 2000}
    Using the function dir:
    ['__doc__', '__init__', '__module__', 'brand', 'price']
    
  • An attribute error can also occur while using a submodule from a particular package. While we import a Python package, it is not necessary that all its submodules will also get imported automatically and this generally raises an attribute error. For example:

    #Find cubic root of 27 using cbrt() function
    import scipy
    cb=scipy.special.cbrt([27])
    print(cb)

    Output

    Traceback (most recent call last):
      File "main.py", line 2, in <module>
        cb=scipy.special.cbrt([27])
    AttributeError: 'module' object has no attribute 'special'
    

In the above code, we have imported the package scipy to find the cube root of a number using its ‘special’ submodule. But only importing scipy did not import its submodule special and hence raised the attribute error. To avoid such situations, we need to explicitly import the submodule special by replacing the code inline 2 by import scipy.special. This will remove the attribute error.

These are some ways that can help us to avoid and remove the attribute errors from our code.

Also, read: Check if an object has an attribute in Python

Leave a Reply

Your email address will not be published. Required fields are marked *