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.
print(hasattr("text", "upper")) # True
Try it
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.
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
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, sohasattr()can have side effects or be slow. - A raising property can hide. If a property raises
AttributeErrorinternally (even by accident, such as a typo inside it),hasattr()reportsFalse, which can mask bugs. - Check-then-use is racy and wasteful.
if hasattr(x, "a"): x.a()looksaup twice. Atry/except AttributeErroraround the call is more Pythonic, unless the guarded code could itself raiseAttributeErrorfor 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.
Related
getattr(),setattr(),delattr(),isinstance(),dir()- Lessons: Classes, Exceptions