Object does not have the specified attribute
Raised when an attribute reference or assignment fails. This usually means you are trying to access a method or property that does not exist for the object's type.
- 1A typo in the attribute or method name.
- 2Trying to access an attribute on an object that is `None`.
- 3Confusing the methods of one type with another (e.g., calling a list method like `.append()` on an integer).
This error occurs when calling the list method `.append()` on an integer, which does not have this attribute.
x = 10 x.append(5) # Integers do not have an 'append' method
expected output
Traceback (most recent call last): File "<stdin>", line 2, in <module> AttributeError: 'int' object has no attribute 'append'
Fix 1
Ensure the object is of the correct type
WHEN When a variable could hold objects of different types, especially `None`.
my_list = None
# my_list.append(5) -> would cause AttributeError
if my_list is None:
my_list = []
my_list.append(5)
Why this works
By checking if the object is `None` and initializing it if so, you ensure it's a list before calling list methods on it.
Fix 2
Check for attribute existence with `hasattr()`
WHEN When dealing with objects of unknown or dynamic structure, though this is less common.
x = 10
if hasattr(x, "append"):
x.append(5)
else:
print(f"Object of type {type(x).__name__} has no 'append' attribute.")
Why this works
`hasattr()` safely checks if an object has a given attribute without raising an error, allowing for conditional logic.
x = 10 x.append(5) # AttributeError: int has no attribute append
try:
x.some_method()
except AttributeError as e:
print(f"Object missing attribute: {e}")if hasattr(obj, "method"):
obj.method()
else:
pass # safe fallback✕ Adding the missing attribute to an object via monkey-patching
This can have wide-ranging, unexpected side effects and makes the code's behavior unpredictable and hard to debug.
cpython/Objects/object.c
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev