Python Function Reference

hasattr

Check whether an object has an attribute with the given name.

Python 3.13
hasattr(object, name)
object
The object to check.
Any
name
The name of the attribute.
str

Return value

True if the attribute exists, otherwise False.

Examples

Checking that a method exists

Python 3.13
print(hasattr('hello', 'upper'))
True

Missing attribute

Python 3.13
print(hasattr('hello', 'size'))
False

Details

hasattr tries to get the attribute and returns False only if AttributeError is raised; other errors inside a property propagate. If you need the attribute right away, getattr(obj, name, default) is simpler.

See also