inspection

getattr()

Returns the value of the named attribute of object. If the attribute is missing, returns default (if given) or raises AttributeError.

getattr(object, name, default=...)

Parameters

Parameter Purpose
object Target object
name Attribute name as a string
default Fallback if attribute is missing

Examples

getattr('abc', 'upper')()

Returns 'ABC'

getattr(obj, 'x', 0)

Returns 0 if obj.x doesn't exist

handler = getattr(self, f'do_{cmd}', None)

Dynamic dispatch pattern

Gotcha

Without default, AttributeError propagates from property getters too — that error may hide the real problem inside the property.

Related built-ins

← All Python built-ins