Yandex

Python hasattr() Function – Check If an Object Has an Attribute



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 an AttributeError.

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 or False.
  • 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")


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M