getattr(object, name)

getattr(object, name, default)

The getattr() function returns the value of a named attribute of an object. If the attribute is not found, it returns the default value provided.

Parameters

The getattr() function accepts these parameters:

  • object - the object whose named attribute value is returned
  • name - a string containing the attribute’s name
  • default (optional) — the value returned if the named attribute is not found

This function is useful when the object or attribute name may vary.

Return Value

  • The value of the named attribute of the given object
  • default, if the named attribute is not found
  • AttributeError, if the named attribute is not found and no default value is provided

Examples

getattr(myobj, 'myattr')
# Equivalent to
myobj.myattr

To set an attribute, use setattr(). To delete an attribute, use delattr(). To check for an attribute’s existence, use hasattr().