hasattr()

Checks whether an object has an attribute or method with the given name. Returns True or False.

Returns
True or False.
On this page

Example

#
Python
class Quiz:
    def __init__(self):
        self.questions = 5

    def check(self, answer):
        return answer == "B"

quiz = Quiz()

print(hasattr(quiz, "questions"))
print(hasattr(quiz, "check"))
print(hasattr(quiz, "timer"))
print(hasattr("text", "upper"), hasattr(42, "upper"))
Resultsaved result, you can check it
True
True
False
True False

Definition and usage

#

The hasattr(object, "name") function returns True if the object has an attribute with that name, and False otherwise. This counts attributes of the object itself, its class, and its base classes, as well as methods.

Internally, hasattr() simply tries to read the attribute through getattr() and checks whether an AttributeError showed up. That means for a property defined with @property, the getter code actually runs, and any other exception raised inside it is not caught.

Checking with hasattr() is useful with objects of different types, for example to call a method only where it exists. This approach is called duck typing: what matters is what the object can do, not its class. Often, though, it is shorter to just write getattr(object, "name", None) directly, or a try block with except AttributeError.

Syntax

#
Syntax
hasattr(object, name)

Parameters

#
  • object

    any object

    The object being checked.
  • name

    str

    The name of the attribute or method.

More examples

#
Duck typing: call a method if it exists
Python
class Video:
    def play(self):
        return "Playing video"

class Quiz:
    def start(self):
        return "Starting quiz"

class Article:
    pass

for item in [Video(), Quiz(), Article()]:
    if hasattr(item, "play"):
        print(item.play())
    elif hasattr(item, "start"):
        print(item.start())
    else:
        print(f"{type(item).__name__}: no action")
Resultsaved result, you can check it
Playing video
Starting quiz
Article: no action
hasattr() runs the property code
Python
class Profile:
    @property
    def avatar(self):
        print("Looking for an avatar...")
        raise AttributeError("no avatar")

profile = Profile()
print(hasattr(profile, "avatar"))
Resultsaved result, you can check it
Looking for an avatar...
False

Good practices

#
  • Instead of the pair hasattr() plus a read, one call to getattr(object, "name", None) is often enough.
  • Dictionary keys are not attributes. To check whether a key exists, use the in operator.
  • If what matters is the object's type rather than which methods it has, use isinstance().

Related entries

#

Spotted a mistake or missing an example? Write to us.