Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Josh Felise
The Python "AttributeError: 'bool' object has no attribute" occurs when we try
to access an attribute on a boolean value (True
or False
). To solve the
error, track down where you are setting the value to a boolean or use the
hasattr()
method to check for the attribute's existence.
Here is an example of how the error occurs.
example = True # ⛔️ AttributeError: 'bool' object has no attribute 'my_attribute' print(example.my_attribute)
We are trying to access an attribute on a boolean (True
or False
) instead of
on an object.
If you print()
the value you are accessing the attribute on, it will be a
boolean.
For example, you might be returning a boolean value from a function somewhere in your code and assigning that to the variable instead of an object.
def get_obj(): return False # 👇️ False example = get_obj() # ⛔️ AttributeError: 'bool' object has no attribute 'items' print(example.items())
The get_obj
function in the example returns a boolean, so the example
variable gets assigned a False
value which causes the error.
If you need to check whether an object contains an attribute, use the hasattr
function.
example = True if hasattr(example, 'my_attribute'): print(example.my_attribute) 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.
Using the 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 a boolean value in your code.
class Employee(): def __init__(self, name): self.name = name employee = Employee('Alice') # 👇️ assignment to boolean here (cause of the error) employee = True # ⛔️ AttributeError: 'bool' object has no attribute 'name' print(employee.name)
The example shows how the employee
variable stored an object at first, but got
assigned a boolean value somewhere in our code which caused the error.
If we remove the line that assigns a boolean value to employee
in the example,
the error wouldn't occur.
class Employee(): def __init__(self, name): self.name = name employee = Employee('Alice') print(employee.name) # 👉️ Alice
If you print()
the value you are accessing the attribute on and get a True
or False
value back, you are either assigning the incorrect value to a
variable or you have a re-assignment somewhere in your code that overrides the
object with a boolean value.