Python hasattr()
Function
The hasattr() function in Python is used to check if an object has a specific attribute. It returns True
if the attribute exists and False
otherwise. This is especially useful when working with dynamic objects or avoiding errors when accessing unknown attributes.
Syntax
hasattr(object, name)
Parameters:
object
– The object you want to check.name
– The name of the attribute (as a string).
Returns:
True
if the attribute exists.False
if it doesn’t exist or raises anAttributeError
.
Example: Basic Usage
class Person:
name = "Alice"
p = Person()
print(hasattr(p, "name")) # True
print(hasattr(p, "age")) # False
True
False
Use Case: Avoiding AttributeError
Instead of directly accessing an attribute which may or may not exist, use hasattr()
to check first:
if hasattr(p, "name"):
print(p.name)
else:
print("No name attribute found")
Example: Working with __dict__
Attributes
class Car:
def __init__(self):
self.brand = "Tesla"
c = Car()
print(hasattr(c, "brand")) # True
print(hasattr(c, "__dict__")) # True
print(hasattr(c, "model")) # False
True
True
False
Common Mistakes
- Passing a non-string as the attribute name will raise a
TypeError
. - Returns
False
for properties that raise exceptions during lookup.
Interview Tip
hasattr()
is commonly used in dynamic programming, frameworks like Django, and when working with JSON-like objects or user-defined classes.
Summary
hasattr()
checks if an object has an attribute.- Returns
True
orFalse
. - Used to prevent
AttributeError
. - Common in introspection and dynamic object handling.
Practice Problem
Create a class Book
with a title
attribute. Write a program that asks the user for an attribute name and checks whether it exists using hasattr()
.
class Book:
def __init__(self):
self.title = "Python Guide"
b = Book()
attr = input("Enter attribute name to check: ")
if hasattr(b, attr):
print("Attribute exists")
else:
print("Attribute does not exist")