Whether you have written 10 lines of Python or 10,000 lines it is always surprising when you get an AttributeError
exception in your code. By the end of this post you will be well on your way to learning why this happens and how can you fix it.
First, let’s imagine you have a simple Python program like this:
snakes = ['cobra', 'anaconda', 'rattle snake']
snakes.add('boa')
PythonIf you copy this into a file and run it (or use the Python REPL), you will get an error that looks something like this:
Traceback (most recent call last):
File "snakes.py", line 2, in <module>
snakes.add('boa')
AttributeError: 'list' object has no attribute 'add'
PythonWhat does an AttributeError
even mean?
This error means that there is no attribute add
for the list
object. snakes
happens to be a list
object, so this exception is thrown when we called snakes.add('boa')
because there is no function available with that name.
How can I fix the AttributeError
?
Luckily for you, if you get this error you can fix it in a few different ways:
- Check your spelling. Closely examine what attribute you are attempting to call, is it spelled as you intended?
- Check your object. If the attribute you are attempting to call is indeed spelled correctly, then perhaps the object you are trying to call it on is not what you think it is. For example, if we simply change the first line of our program to
snakes = set(['cobra', 'anaconda', 'rattle snake'])
then the error is gone! This is because theset
object has anadd
function. - Check your attribute. If the object that you are calling is also indeed correct, then your last solution is to change the attribute. In this example, we could change the second line of our program to
snakes.append('boa')
and the error would also be gone!
Next time you run into an AttributeError
, don’t fret and run through the 3 checks above to resolve it quickly!
Still can’t figure it out?
One of my favorite ways to debug is to use the breakpoint()
keyword to figure out where my mental model is misaligned with the code.
Simply add breakpoint()
to the line before where the exception is thrown. Continuing with the example above, it would look like this:
snakes = ['cobra', 'anaconda', 'rattle snake']
breakpoint()
snakes.add('boa')
PythonThen when you run the code, the program will stop on the line where breakpoint()
is and it will give you a Python REPL. You can type snakes
and hit enter to see what is in the snakes
variable, or type(snakes)
to see what type of object it is.
Obviously breakpoint()
can come in handy for many debugging scenarios, but certainly is helpful here.
Leave a Reply