Python 3 reference · Built-in Functions

Python hasattr() Function

Return True if an object has an attribute with the given name. It works by calling getattr() and catching AttributeError.

Python 3 Since 3.0

Syntax

hasattr(object, name)

Parameters

ParameterDescription
object Any object.
name The attribute name as a string.

Return value

True or False.

Examples

Check for a methodTry it yourself
print(hasattr("text", "upper"))
print(hasattr([1, 2], "upper"))

Output

True
False
Duck typingTry it yourself
class Duck:
    def quack(self): return "Quack!"

class Robot:
    pass

for thing in [Duck(), Robot()]:
    print(thing.quack() if hasattr(thing, "quack") else "can't quack")

Output

Quack!
can't quack

Version history

VersionChange
Python 3.0Added