AttributeError: 'NoneType' object has no attribute
What it means
A variable you expected to hold a list, a string or another object actually holds None, and None has no methods. Something earlier gave you None: often a method that changes a list in place, a function with no return, or a search that found nothing. The name at the end of the message is the method you tried to use.
1. Saving the result of `append()` or `sort()`
This raises the error
Traceback (most recent call last): File "<exec>", line 3, in <module> AttributeError: 'NoneType' object has no attribute 'append'
The fix
['milk', 'eggs', 'bread']
List methods like append(), sort() and reverse() change the list in place and return None. Assigning that result replaced your list with None.
2. A function that forgot to `return`
This raises the error
Traceback (most recent call last): File "<exec>", line 5, in <module> AttributeError: 'NoneType' object has no attribute 'title'
The fix
Hello World
A function without return gives back None. Returning the cleaned text hands it to the caller.
3. A search that found nothing
This raises the error
Traceback (most recent call last): File "<exec>", line 4, in <module> AttributeError: 'NoneType' object has no attribute 'group'
The fix
No number found
re.search() returns None when nothing matches, and so do dict.get() and many find() style methods. Check the result before using it.
When you see this error, check
- Print the variable just before the failing line. If it shows
None, trace back to where it was set. - Never assign the result of
append(),sort(),reverse()orrandom.shuffle(). - Check that your function reaches a
returnon every path. - Test search results with
if result:before calling methods on them.
Related errors
All Python errors · How to read a traceback · Step through your code