Skip to content

/errors/python/attributeerror-nonetype-object-has-no-attribute

AttributeError: 'NoneType' object has no attribute 'x'

verified onenvironmentlocal · linux 6.18.44-fc-v140 x64 · GNU bash 5.2.21 · Python 3.11.17updated
tool
Python
exit code
1
versions
Python 3.x
os
any

AttributeError: 'NoneType' object has no attribute 'x' means the variable before the dot is None, so the attribute x does not exist. The bug is almost never on the failing line: find where the value became None. Typical sources are a function without return, an in-place method whose result was assigned, or a lookup with no match.

Reproduce it

bash
python3 -c "None.foo"

Output · exit 1

Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'foo'

The three usual sources:

bash
python3 - <<'PY'
import re

def load():
    data = [3, 1, 2]

items = [3, 1, 2].sort()
m = re.match(r'\d+', 'abc')
for name, value in [('function', load()), ('sort', items), ('match', m)]:
    try:
        value.append(1)
    except AttributeError as e:
        print(name, '->', e)
PY

Output

function -> 'NoneType' object has no attribute 'append'
sort -> 'NoneType' object has no attribute 'append'
match -> 'NoneType' object has no attribute 'append'

Fix it

bash
python3 - <<'PY'
import re

def load():
    return [3, 1, 2]

items = sorted(load())
m = re.match(r'\d+', 'abc')
print(items)
print(m.group() if m is not None else 'no match')
PY

Output

[1, 2, 3]
no match

list.sort() sorts in place and returns None; use sorted() when you need the new list. dict.get(key) returns None for a missing key; pass a default, d.get(key, default).

Sources