Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python hasattr() function

Reference for Python hasattr(): test whether an object has an attribute by name, how it relates to getattr, properties that raise, and EAFP style alternatives.

hasattr(obj, "name") returns True if obj.name can be read without raising AttributeError, and False otherwise. It is implemented by actually trying getattr(obj, name) and catching that one exception.

It suits quick feature checks, such as "does this object have a close method?". In many cases, simply using the attribute inside a try/except AttributeError block (the EAFP style) is more robust and avoids looking the value up twice.

Python
print(hasattr("text", "upper"))
# True

Try it

Python Checking for attributes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Properties, errors and EAFP

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
hasattr(object, name)
Name Description
object The object to inspect.
name The attribute name as a string.

Return value: True or False.

Raises: TypeError if name is not a string. Exceptions other than AttributeError raised while looking up the attribute are not caught.

Usage notes

  • It runs the lookup. Properties and __getattr__ code really execute, so hasattr() can have side effects or be slow.
  • A raising property can hide. If a property raises AttributeError internally (even by accident, such as a typo inside it), hasattr() reports False, which can mask bugs.
  • Check-then-use is racy and wasteful. if hasattr(x, "a"): x.a() looks a up twice. A try/except AttributeError around the call is more Pythonic, unless the guarded code could itself raise AttributeError for another reason.
  • Prefer getattr(obj, name, default) when you want the value or a fallback in a single step.
  • Instance vs class. An attribute assigned only in __init__ exists on instances but not on the class.
  • Duck typing. For capabilities, isinstance() with an abstract base class (collections.abc) often expresses intent better than probing names.
  • Modules work too: hasattr(math, "cbrt") is a common way to check for newer features.