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
hasattr()
Returns True if the object has an attribute with the given name. Implemented by calling getattr() and catching AttributeError.
isinstance()
Returns True if the object is an instance of classinfo (a class or tuple of classes). Respects the class hierarchy — subclasses count.
type()
Returns the type of an object, or dynamically creates a new type when called with three arguments. type(x) is the runtime class of x.
len()
Returns the number of items in a container. Calls the object's __len__ method.