/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
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:
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)
PYOutput
function -> 'NoneType' object has no attribute 'append' sort -> 'NoneType' object has no attribute 'append' match -> 'NoneType' object has no attribute 'append'
Fix it
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')
PYOutput
[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
Related pages
errors · pythonTypeError: 'NoneType' object is not subscriptablePython raises this TypeError when you index a value that is None, often the result of list.sort(), dict.get() or re.match(). Find where None comes from.errors · pythonUnboundLocalError: cannot access local variable 'x' where it is not associated with a valuePython raises UnboundLocalError when a function assigns to a name that is also global: the name becomes local. Fix it with global, nonlocal, or pass it in.errors · pythonKeyError: 'key' in PythonPython raises KeyError when you read a dict key that does not exist. Check the key with in, read it with dict.get(key, default), or fix the spelling or type.