AttributeError: 'NoneType' object has no attribute 'x' means you called a method or accessed an attribute on None. None is a single value meaning “no object”; it has no methods or attributes. This error often appears when a function returns None and you treat the result as if it were a real object. This guide explains causes and fixes.
What this error means
In Python, only objects have attributes and methods. None is not such an object—it is the return value of functions that do not explicitly return something, and it is often used to mean “missing” or “not found”. If you write x.something and x is None, you get AttributeError: 'NoneType' object has no attribute 'something'. Related issues: NoneType not iterable, NoneType not subscriptable, NoneType has no len().
Common causes
- Forgot to return. A function builds an object but does not
returnit, so it implicitly returnsNone. The caller then uses the result and gets this error. - Wrong variable or branch. You expect an object but the variable is
Nonebecause another branch of code set it toNone, or a helper returnedNonefor “not found”. - Optional return. Some functions return
Nonewhen they have nothing to return (e.g. “no match”). The caller must check before using the result.
Example that causes the error
def get_user():
user = {'name': 'Alice'}
# Forgot to return user
result = get_user()
print(result.name) # AttributeError: 'NoneType' has no attribute 'name'
Fix 1: return the object from the function
def get_user():
user = {'name': 'Alice'}
return user
result = get_user()
print(result['name']) # OK
Fix 2: check for None before using attributes or methods
When a value might be None, guard before use:
result = some_function()
if result is not None:
print(result.some_attribute)
else:
print("Result is None")
Fix 3: use hasattr() only when you need to test attributes
hasattr(obj, 'name') returns False if obj is None (None has no attributes). Prefer if obj is not None when the issue is “might be None”.
result = some_function()
if result is not None and hasattr(result, 'some_attribute'):
print(result.some_attribute)
Next steps: Errors & Exceptions · NoneType not iterable · Functions