Editor

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

Broken
shopping = ['milk']
shopping = shopping.append('eggs')
shopping.append('bread')
print(shopping)
Output
Traceback (most recent call last):
  File "<exec>", line 3, in <module>
AttributeError: 'NoneType' object has no attribute 'append'

The fix

Fixed
shopping = ['milk']
shopping.append('eggs') # changes the list, returns None
shopping.append('bread')
print(shopping)
Output
['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.

Try fixing it yourself in the editor

2. A function that forgot to `return`

This raises the error

Broken
def clean(text):
text.strip().lower()
result = clean(' Hello World ')
print(result.title())
Output
Traceback (most recent call last):
  File "<exec>", line 5, in <module>
AttributeError: 'NoneType' object has no attribute 'title'

The fix

Fixed
def clean(text):
return text.strip().lower()
result = clean(' Hello World ')
print(result.title())
Output
Hello World

A function without return gives back None. Returning the cleaned text hands it to the caller.

Try fixing it yourself in the editor

3. A search that found nothing

This raises the error

Broken
import re
text = 'Order number: none yet'
match = re.search(r'\d+', text)
print(match.group())
Output
Traceback (most recent call last):
  File "<exec>", line 4, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

The fix

Fixed
import re
text = 'Order number: none yet'
match = re.search(r'\d+', text)
if match:
print(match.group())
else:
print('No number found')
Output
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.

Try fixing it yourself in the editor

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() or random.shuffle().
  • Check that your function reaches a return on every path.
  • Test search results with if result: before calling methods on them.

All Python errors · How to read a traceback · Step through your code