AttributeError: 'NoneType' object has no attribute
AttributeError: 'NoneType' object has no attribute in Python means something returned None and you called a method on it. Usually a lookup that failed, or a function that forgot to return.
How do I fix AttributeError: 'NoneType' object has no attribute?
To fix AttributeError: 'NoneType' object has no attribute in Python, locate the line causing the error and check the values right before it runs. Most occurrences happen because of a function with no return statement. Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.
What does AttributeError: 'NoneType' object has no attribute mean?
None is Python's empty value and it has almost no attributes. The message tells you the attribute you tried to reach, which reveals what type you expected. The interesting question is always where the None came from.
Why does AttributeError: 'NoneType' object has no attribute happen?
1. A function with no return statement
A Python function without an explicit return gives back None. Easy to miss when the function is long.
Breaks
def build_name(first, last):
full = first + " " + last
name = build_name("Ada", "Lovelace")
print(name.upper())Works
def build_name(first, last):
return first + " " + last2. Assigning the result of a mutating method
list.sort(), list.append() and list.reverse() change the list in place and return None. That None return is the convention marking a mutating method.
Breaks
names = names.sort()Works
names.sort() # in place
# or
names = sorted(names) # new list3. dict.get() on a missing key
get returns None rather than raising, which is its point โ but None then flows onward until something uses it.
Breaks
city = config.get("city").upper()Works
city = config.get("city", "").upper()4. A regex that did not match
re.search returns None when there is no match, not an empty match object.
Breaks
digits = re.search(r"\d+", text).group()Works
m = re.search(r"\d+", text)
digits = m.group() if m else ""How to find it in your own code
Print the variable just before the failing line to confirm it is None, then trace back to what produced it. If a function is meant to return something, check every branch actually does โ an if with no else returns None silently.
Try it: fix this bug
easyget_setting_with_fallback({'retries': None}, 'retries', 3) returns None instead of 3.
def get_setting_with_fallback(config, key, default_val):
return config.get(key, default_val)More challenges with this error
Each of these challenges runs into this error or pattern. Find the bug and fix it in your browser โ no install, no account needed.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.