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
getattr()
Returns the value of the named attribute of object. If the attribute is missing, returns default (if given) or raises 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.