AttributeError: A Step By Step Troubleshooting Guide!

In this article, let us learn what causes AttributeError and see how we can fix that and get our code up and running again!

Troubleshooting any errors will include the following steps

  • Step#1: Understand the error and its causes
  • Step#2: Figure out which of the causes actually led to the error in your particular case
  • Step#3: Apply the Fix, and test your code to confirm.
  • Step#4: Party!

Let us start by understanding the AttributeError and its causes!

Step#1: Understanding AttributeError and its Causes

Before getting into learning what AttributeError is, we must first understand what an attribute is!

What is an Attribute?

As you might have learned in your fundamentals of object-oriented programming course, each class is made up of a combination of variables and functions. Hence these variables and functions can be thought of as building blocks of any given class

Attributes” is just a fancy way of saying “building blocks of a class” (or should I say “lazy way of saying”!!)

For example, the following class has 3 attributes

class MyClass:
    def __init__(self, a, b):
        self.a = a
        self.b = b
  • the variable ‘a‘ is attribute#1
  • the variable ‘b‘ is attribute#2 and
  • the method ‘__init__( )‘ is attribute#3

We can store values in these variables a & b and read them back as shown below

>>> my_object = MyClass(1, 2)
>>> print(my_object.a)
1
>>> print(my_object.b)
2

As you can see in the code above we have successfully managed to retrieve variables (a.k.a attributes) a & b.

Now let’s try to break the code!

>>> print(my_object.c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyClass' object has no attribute 'c'

And voila! We got an AttributeError!

So, what happened here?!

What Is AttributeError?

As you might have guessed, we only have a & b in MyClass and we don’t have any attribute named c, and hence when we tried to access an attribute that is not present in MyClass we ended up with an AttributeError !!

A short one-line explanation would be

AttributeError is an exception that is raised by Python when the attribute we are trying to access does not exist.

embeddedinventor.com

Now that we have a good understanding of what AttributeErrors are, let us see when/why/how this error occurs and how to actually fix that!

If you are in the first steps of your Python journey and you are not 100% clear about what exceptions are, I strongly recommend reading our article on Exceptions before proceeding with this one!

Exceptions in Python: Explained for Beginners!

There we have explained the concept of exceptions from a beginner perspective with the goal that you will leave away with an intuitive feeling of what exceptions actually are and what their place is in the world of programming!

What Causes AttributeError?

During everyday programming, there are several causes that might lead to AttributeErrors, the 3 most common causes are

  1. Misspelling a keyword or an attribute name
  2. Incorrect indentation of code
  3. Calling a Function on an invalid object

Let us move on to Step#2 and figure out which of these actually caused the error in your particular situation and how to go about fixing that!

Step#2: Figuring Out the Exact Cause in Your Situation

Before getting into that here is a pro tip for you, to fix not just AttributeError but any error in Python. Whenever your program crashes with an Exception, (take a deep breath and) have a look at the huge wall of error text that just got printed on your screen!

There is actually a lot of information contained in the error message, if you wish to learn the tricks then set aside 10mins of your time and read the following article!

Python: Details contained in an Exception

For visual learners out there we have also made an interesting video on that topic!

Coming back to the topic let us take a closer look at each of these causes so that you can figure out which one of these caused the problem for your particular case!

Cause#1: Calling a Method on an Object that does not support it.

This is by far the most common cause of AttributeError, so let’s tackle it first!

Consider the code below

>>> a = 5
>>> a.append(2)

Running this code will lead to AttributeError as shown below

Traceback (most recent call last):
  File "/home/main.py", line 2, in <module>
    a.append(2)
AttributeError: 'int' object has no attribute 'append'

Since a lot of effort has been put into the development of Python to make it feel more like plain English, as a beginner, it is perfectly reasonable to expect append to make 5 into 52!

But then 5 is an integer and int class does not have an append method!

Fix for Cause#1

If you are working with any object and you want to see what methods it supports then you can use 2 inbuilt functions to figure out what methods it supports

  1. dir( )
  2. help( )

Both these methods are explained in detail with examples in the next section, I suggest reading on cause#2 as causes #1 and #2 are very interrelated!

Cause#2: Misspelling a keyword or an attribute name

This is the 2nd most common cause of AttributeError, so let’s tackle it next!

Can you see what’s wrong with the following program? Take a guess

class MyClass:
    def my_func(self):
        pass
    
my_obj = my_class
print(my_obj.my_fnc())

Yes, you are right!

I have misspelled the function name here!

Python interpreter is smart enough to point that out for us in the error message too as shown below!

Traceback (most recent call last):
  File "/home/main.py", line 6, in <module>
    print(my_obj.my_fnc(self))
AttributeError: type object 'MyClass' has no attribute 'my_fnc'. Did you mean: 'my_func'?

In this case, the class is our own code, hence we can refer back and fix it correctly, what if we are using some Python’s in-built class or an external library and we ran into AttributeError?

To do that, we are going to need some Patience (not kidding!)

Fix for Cause#2: Learn the correct name of the attribute and fix the Spelling!

This involves 2 steps

Step#1: Get info about the Attributes of the class of interest

Step#2: Fix the spelling

Let us see how to get the necessary information about the attributes class we are working with.

Follow the 4 methods below, to figure out all the necessary info about a given class

Method#1: Listing all attributes of a class

Consider the class below

class MyClass:
    def __init__(self, a, b):
        self.a = a
        self.b = b
    def my_method(self):
        print("Inside my_method()")

Let us make an object of MyClass and play around a bit

>>> my_object = MyClass(1, 2)
>>> print(my_object.a)
1
>>> print(my_object.b)
2
>>> my_object.my_method()
Inside my_method()

Everything ran smoothly as expected.

Now let us say we want to list the attributes of this class, to do that we can use the code snippet below

>>> dir(my_object)

Here dir is short for directory, which is nothing but a list of all the attributes of a given class.

The screenshot below shows the output

As you can see the last 3 entries in the list gives us the attributes of MyClass!

You can safely ignore everything else in the list for now (These are called dunder methods, short for double underscore methods, they are present with all classes and are responsible for some internal working mechanisms to make using Python user-friendly)

Method#2: List just the variables

If you wish to see just the variables, you can do that using the code snippet below.

>>> vars(my_object)
{'a': 1, 'b': 2}

As you can see, we got just the variables instead of all the attributes.

Method#3: Read the inbuilt documentation

You can use the help() function to read what the class contains

>>> help(MyClass)

This will print the blueprint as shown below

If you read above the dotted lines, you will see our class shown, you can also use this with other classes like list or dict (I leave it to you to try those out!)

Once you are done reading press the letter ‘q‘ to quit and get back to the prompt!

Method#4: Read the online documentation

By now, hopefully, you have figured out what attribute you need to use and why your spelling is incorrect, if not just google the name of the class + the word “documentation” and you should find some good resource to refer to!

Once you have figured out the correct name for the variable or function you wish to use using the 4 methods mentioned above, just fix it and you are ready to get going!

If you are sure that the Attribute name is correct, but you are still getting the AttribtueError then read on!

Cause#3: Incorrect indentation of code

This unintentional mistake is common, especially among beginners, and is the 3rd common cause of AttributeError.

Consider the example below.

class Calculator:   
    def __init__(self, a,b):
        self.a = a
        self.b = b
        
        def add(self):
            return self.a + self.b
        def  subtract(self):
            return self.a - self.b
        
myCalc=  Calculator(2,5)

print(myCalc.a)
print(myCalc.add())

This code will produce AttributeError as shown below.

2
Traceback (most recent call last):
  File "/home/main.py", line 13, in <module>
    print(myCalc.add())
AttributeError: 'myCalc' object has no attribute 'add'

As you might already know,

In Python Indentation carries meaning and is part of the language’s syntax

embeddedinventor.com

The language was designed this way to force users to write readable code. Code is written once, but is read multiple times

  • by you in the future,
  • by your teammates
  • if it’s open-source, then by thousands of people!

In the above example, although the indentation syntax is accepted by the Python interpreter, the code does not do what we want to do, this is because the functions add( ) and subtract( ) are defined inside the __init__( ) function and hence it is not visible outside it and this led to AttributeError as Python could not find any attribute named add( )

If your indentation was not even syntactically correct (say you used different spaces in different lines) you will get an error like this instead.

IndentationError: unindent does not match any outer indentation level

If you are interested to learn why this syntax is correct and what is the use of having functions declared inside other functions, I suggest looking up “nested functions in Python” on Google!

Fix for Cause#3: Double-check the Indentation!

So again, take a deep breath, go back to your code, try to find any indentation issues, fix those and try running your code again!

I hope by now the AttributeError has vanished!

If so we have reached the end of the road! Don’t forget to celebrate!

For the next step in your Python journey I invite you to master some of the most common errors you will run into in your daily life as a Python developer. We have compiled a list of just 7 exceptions that you need to focus on if you wish to gain mastery of Exceptions in Python!

7 Most Common In-Built Exceptions in Python!

If you are a visual learner here is a YouTube video that we made on that same topic!

And with that, I end this article.

I hope you enjoyed reading this article and found it useful!

Feel free to share it with your friends and colleagues!

If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!

Related Articles

7 Most Common In-Built Exceptions in Python!

Python Exceptions: Explained for Beginners!

Python: When To Use Custom Exceptions? Explained!

Python TypeError: A Step By Step Troubleshooting Guide!

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn