hasattr()
Checks whether an object has an attribute or method with the given name. Returns True or False.
- Returns
TrueorFalse.
Example
#class Quiz:
def __init__(self):
self.questions = 5
def check(self, answer):
return answer == "B"
quiz = Quiz()
print(hasattr(quiz, "questions"))
print(hasattr(quiz, "check"))
print(hasattr(quiz, "timer"))
print(hasattr("text", "upper"), hasattr(42, "upper"))Definition and usage
#The hasattr(object, "name") function returns True if the object has an attribute with that name, and False otherwise. This counts attributes of the object itself, its class, and its base classes, as well as methods.
Internally, hasattr() simply tries to read the attribute through getattr() and checks whether an AttributeError showed up. That means for a property defined with @property, the getter code actually runs, and any other exception raised inside it is not caught.
Checking with hasattr() is useful with objects of different types, for example to call a method only where it exists. This approach is called duck typing: what matters is what the object can do, not its class. Often, though, it is shorter to just write getattr(object, "name", None) directly, or a try block with except AttributeError.
Syntax
#hasattr(object, name)Parameters
#object
any object
The object being checked.name
str
The name of the attribute or method.
More examples
#class Video:
def play(self):
return "Playing video"
class Quiz:
def start(self):
return "Starting quiz"
class Article:
pass
for item in [Video(), Quiz(), Article()]:
if hasattr(item, "play"):
print(item.play())
elif hasattr(item, "start"):
print(item.start())
else:
print(f"{type(item).__name__}: no action")class Profile:
@property
def avatar(self):
print("Looking for an avatar...")
raise AttributeError("no avatar")
profile = Profile()
print(hasattr(profile, "avatar"))Good practices
#- Instead of the pair
hasattr()plus a read, one call togetattr(object, "name", None)is often enough. - Dictionary keys are not attributes. To check whether a key exists, use the
inoperator. - If what matters is the object's type rather than which methods it has, use
isinstance().
Related entries
#- getattr()Reads an object’s attribute by a name given as a string, optionally with a default value.
- isinstance()Checks whether an object is of a given type, or of a subtype of it.
- dir()Returns a list of the names of an object’s attributes and methods.
- @propertyTurns a method into an attribute: the value is computed on read, and an optional setter controls writes.
- type()Returns the type of an object.
Spotted a mistake or missing an example? Write to us.