AttributeError
PythonERRORNotableRuntime ErrorHIGH confidence

Object does not have the specified attribute

What this means

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.

Why it happens
  1. 1A typo in the attribute or method name.
  2. 2Trying to access an attribute on an object that is `None`.
  3. 3Confusing the methods of one type with another (e.g., calling a list method like `.append()` on an integer).
How to reproduce

This error occurs when calling the list method `.append()` on an integer, which does not have this attribute.

trigger — this will error
trigger — this will error
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`.

Ensure the object is of the correct type
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.

Check for attribute existence with `hasattr()`
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.

Code examples
Triggerpython
x = 10
x.append(5)  # AttributeError: int has no attribute append
Handle with try/exceptpython
try:
    x.some_method()
except AttributeError as e:
    print(f"Object missing attribute: {e}")
Avoid with hasattr()python
if hasattr(obj, "method"):
    obj.method()
else:
    pass  # safe fallback
What not to do

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.

Sources
Official documentation ↗

cpython/Objects/object.c

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors