hasattr() Has attribute
Last updated: 2026-09-22
hasattr() Has attribute
hasattr(obj, name) reports whether obj has an attribute called name.
| Category | Built-in Functions |
|---|---|
| Kind | Built-in Function |
| Python Version | all |
📝 Syntax
hasattr(object, name)
⚙️ Parameters
| object Required | The object to check for the attribute (any object). |
|---|---|
| name Required | Attribute name as a string, e.g. 'attr'. |
Returns:A bool: True if the object has the named attribute, otherwise False.
💥 Raises
TypeError— Raised when name is not a string.
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
True
False
🏷️ Related Built-in Functions
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QIf hasattr(obj, 'x') returns True, what does that mean?
AIt means obj has an attribute named x (including ones inherited from a parent class), but it does not guarantee the value is non-None, nor that it is callable.
QWhat is the difference between hasattr and getattr?
Ahasattr only checks existence and returns a boolean; getattr fetches the value and raises an AttributeError if it is missing (unless a default is given).
QMust the attribute name be hardcoded?
ANo — the name in hasattr(obj, attr_name) can be a variable, which suits dynamically checking an object's capabilities.
QCan hasattr check a method?
AYes, a method is also an attribute, so hasattr(obj, 'method_name') returns True; combine it with callable() to further confirm it is callable.