Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by João Ferrão
The Python "AttributeError: 'int' object has no attribute" occurs when we try to access an attribute that doesn't exist on an integer. To solve the error, make sure the value is of the expected type before accessing the attribute.
Here is an example of how the error occurs.
example = 123 print(type(example)) # 👉️ <class 'int'> # ⛔️ AttributeError: 'int' object has no attribute 'startswith' result = example.startswith('12')
We tried to call the startswith()
method on an integer and got the error.
If you print()
the value you are accessing the attribute on, it will be an
integer.
To solve the error in the example, we would have to convert the integer to a
string
to be able to access the string-specific startswith()
method.
example = 123 result = str(example).startswith('12') print(result) # 👉️ True
Most commonly the error is caused by reassigning a variable to an integer somewhere in your code.
nums = [1, 2, 3] # 👇️ reassignment of nums to an integer nums = 1 # ⛔️ AttributeError: 'int' object has no attribute 'append' nums.append(4) print(nums)
We set the nums
variable to a list initially but later assigned an integer to
it.
To solve the error in this scenario, we have to remove the reassignment or correct it.
nums = [1, 2, 3] nums.append(4) print(nums) # 👉️ [1, 2, 3, 4]
If you need to check whether an object contains an attribute, use the hasattr
function.
example = 5 if hasattr(example, 'lower'): print(example.lower()) else: print('Attribute is not present on object') # 👉️ this runs
The hasattr function takes the following 2 parameters:
Name | Description |
---|---|
object | The object we want to test for the existence of the attribute |
name | The name of the attribute to check for in the object |
The hasattr()
function returns True
if the string is the name of one of the
object's attributes, otherwise False
is returned.
hasattr
function would handle the error if the attribute doesn't exist on the object, however you still have to figure out where the variable gets assigned an integer value in your code.A good way to start debugging is to print(dir(your_object))
and see what
attributes the object has.
Here is an example of what printing the attributes of an integer
looks like.
example = 5 # [..., 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'...] print(dir(example))
If you pass a class to the dir() function, it returns a list of names of the classes' attributes, and recursively of the attributes of its bases.
To solve the error, either convert the value to the correct type before accessing the attribute, or correct the type of the value you are assigning to the variable before accessing any attributes.