hasattr()
Returns True if an object has an attribute or method with the given name, and False if not. The name is passed as a string.
hasattr(object, name)hasattr(obj, "name") checks whether obj.name would work. It returns True or False instead of crashing with AttributeError.
Use it when objects of different kinds come into the same function and only some of them have a feature, for example only some shapes have a radius, or only some objects can be closed.
The name is a string, written in quotes. Behind the scenes hasattr() simply tries getattr(obj, name) and returns False if that raises AttributeError.
Parameters
| Parameter | What it is |
|---|---|
objectrequired | The object to inspect: any value, class or module. |
namerequired | The attribute name, as a string: "upper", "price". |
Return value
True or False.
Examples
1Methods of built-in types
print(hasattr("text", "upper"))
print(hasattr(42, "upper"))
print(hasattr([1, 2], "append"))True False True
2Attributes of your own objects
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
item = Product("Lamp", 39.9)
print(hasattr(item, "price"))
print(hasattr(item, "discount"))
item.discount = 0.1
print(hasattr(item, "discount"))True False True
Attributes can be added to an object at any time, and hasattr() sees them at once.
3Handle different kinds of shapes
class Circle:
def __init__(self, radius):
self.radius = radius
class Square:
def __init__(self, side):
self.side = side
for shape in [Circle(2), Square(3)]:
if hasattr(shape, "radius"):
print("Circle, radius", shape.radius)
else:
print("Square, side", shape.side)Circle, radius 2 Square, side 3
4Use an optional feature if it is there
class Printer:
def print_page(self, text):
print("Printing:", text)
class ColorPrinter(Printer):
def set_color(self, color):
print("Color set to", color)
for device in [Printer(), ColorPrinter()]:
if hasattr(device, "set_color"):
device.set_color("blue")
device.print_page("report")Printing: report Color set to blue Printing: report
Common mistakes
Forgetting the quotes around the name
hasattr(item, price) looks for a variable called price and raises NameError if there is none. The name must be a string.
class Product:
price = 10
item = Product()
try:
print(hasattr(item, price))
except NameError:
print("NameError: write the name in quotes")
print(hasattr(item, "price"))NameError: write the name in quotes True
Checking first, then reading anyway
if hasattr(obj, "x"): value = obj.x else: value = None takes two steps. getattr(obj, "x", None) does the same in one. See getattr().
Questions people ask
How do I check if a dictionary has a key?
Use "key" in my_dict, not hasattr(). Dictionary keys are not attributes.
Is hasattr() or try/except better?
Both are fine. If you are going to use the attribute right away, try: obj.x ... except AttributeError: or getattr(obj, "x", default) avoids looking it up twice.
Does hasattr() find methods too?
Yes. Methods are attributes, so hasattr("abc", "split") is True. Use callable() to tell methods from data.