inspection

hasattr()

Returns True if the object has an attribute with the given name. Implemented by calling getattr() and catching AttributeError.

hasattr(object, name)

Parameters

Parameter Purpose
object Target object
name Attribute name as a string

Examples

hasattr('abc', 'upper')

Returns True

hasattr([], 'foo')

Returns False

hasattr(obj, '__len__')

Checks if len(obj) will work

Gotcha

Only AttributeError is caught (Python 3.2+) — other exceptions from properties propagate. Prefer EAFP (try/except) for critical paths.

Related built-ins

← All Python built-ins