Adapt to optional object attributes
Feature detection
Python · Function
Checks whether an object has an attribute with a specified string name. It returns True when the lookup succeeds and False when it raises AttributeError.
hasattr() checks an object for an attribute whose name is supplied as a string. It returns True when the attribute lookup succeeds and False when the lookup raises AttributeError; internally, it performs the equivalent of a getattr() lookup for this test.
hasattr(object, name, /)| Name | Type | Description |
|---|---|---|
object | object | Object whose attributes are checked. |
name | str | String containing the attribute name to test. |
True if name identifies an attribute of object; otherwise False.
class User:
name = "Ada"
user = User()
print(hasattr(user, "name"))
print(hasattr(user, "email"))The first call finds the class attribute and prints True; the second finds no such attribute and prints False.
Feature detection
Defensive access
hasattr() takes an object and a string naming an attribute. It returns True if that attribute exists and False otherwise.
Follow-up: How does it determine the result? It effectively calls getattr(object, name) and checks whether AttributeError is raised.
The attribute name must be provided as a string, such as "name". The function returns a Boolean indicating whether lookup succeeds.
Follow-up: What happens if the lookup raises a different exception? The documented test is specifically based on AttributeError, so callers should not assume every lookup failure becomes False.
hasattr() is useful when code must support objects with optional attributes without first accessing a missing attribute directly. It is a predicate only; it does not return the attribute value.
Follow-up: Which built-in can retrieve the value instead? getattr() performs named attribute lookup and can also accept a default value.
getattr()setattr()delattr()