AttributeError: 'NoneType' object has no attribute 'X' means youβre calling a method or accessing a property on None. Something you expected to be an object is actually None.
What causes this error
- A function returned None β many Python functions return
Noneby default, and methods likelist.sort()andlist.append()modify in-place and returnNone - A variable wasnβt assigned β a conditional branch didnβt set the variable
- A failed lookup β
dict.get()returnsNonefor missing keys
Fix 1: Check for in-place methods
This is the #1 cause:
# β .sort() returns None, not the sorted list
my_list = [3, 1, 2].sort()
my_list.append(4) # AttributeError: 'NoneType'
# β
sort() modifies in-place
my_list = [3, 1, 2]
my_list.sort()
my_list.append(4) # Works
# β
Or use sorted() which returns a new list
my_list = sorted([3, 1, 2])
Same applies to: .append(), .extend(), .insert(), .remove(), .reverse().
Fix 2: Add None checks
result = get_user(user_id)
# β Crashes if user not found
print(result.name)
# β
Check first
if result is not None:
print(result.name)
else:
print("User not found")
Fix 3: Use default values
# β Returns None if key missing
value = my_dict.get('key')
print(value.upper()) # AttributeError if key missing
# β
Provide a default
value = my_dict.get('key', '')
print(value.upper()) # Works β empty string has .upper()
How to find the source
Read the traceback carefully. The line number tells you exactly which variable is None. Then trace backwards to find where it should have been assigned. An AI debugging assistant can help you trace these quickly.
# Add debugging
result = some_function()
print(f"result is: {result}, type: {type(result)}") # See what you actually got
Related fixes: Python MemoryError Β· Python TypeError Β· Python cheat sheet
Related: Pip Install Error Fix