Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Python · Function

hasattr

Checks whether an object has an attribute with a specified string name. It returns True when the lookup succeeds and False when it raises AttributeError.

How it works

hasattr() checks an object for an attribute whose name is supplied as a string. It returns True when the attribute lookup succeeds and False when the lookup raises AttributeError; internally, it performs the equivalent of a getattr() lookup for this test.

Syntax

hasattr(object, name, /)

Parameters

NameTypeDescription
objectobjectObject whose attributes are checked.
namestrString containing the attribute name to test.

Returns

True if name identifies an attribute of object; otherwise False.

Key points

  • It accepts exactly an object to inspect and a string containing the attribute name.
  • A successful match produces True; an absent attribute produces False.
  • Its test is based on performing the corresponding named attribute lookup.
  • The Boolean result depends on whether that lookup raises AttributeError.
  • The modern signature makes both arguments positional-only.

Common mistakes

  • The check performs attribute access, so custom attribute lookup can run and its behavior can affect the result.

Example: Check whether an attribute exists

class User:
    name = "Ada"

user = User()
print(hasattr(user, "name"))
print(hasattr(user, "email"))

The first call finds the class attribute and prints True; the second finds no such attribute and prints False.

When to use it

Adapt to optional object attributes

Feature detection

Avoid direct access to a potentially missing attribute

Defensive access

Interview questions

QWhat does hasattr() do?

hasattr() takes an object and a string naming an attribute. It returns True if that attribute exists and False otherwise.

Follow-up: How does it determine the result? It effectively calls getattr(object, name) and checks whether AttributeError is raised.

QWhat types of arguments does hasattr() expect?

The attribute name must be provided as a string, such as "name". The function returns a Boolean indicating whether lookup succeeds.

Follow-up: What happens if the lookup raises a different exception? The documented test is specifically based on AttributeError, so callers should not assume every lookup failure becomes False.

QWhen would you use hasattr() rather than direct attribute access?

hasattr() is useful when code must support objects with optional attributes without first accessing a missing attribute directly. It is a predicate only; it does not return the attribute value.

Follow-up: Which built-in can retrieve the value instead? getattr() performs named attribute lookup and can also accept a default value.

  • getattr()
  • setattr()
  • delattr()

Source: Built-in functions. Checked 2026-10-16.