Python Glossary Русский

all Python 3Built-in functionsterm

hasattr

OOP

Returns True if the object has an attribute with the given name. Implemented as a getattr() attempt — checks presence without raising.

Syntax

hasattr(object, name)

hasattr does not inspect the object's structure — it actually fetches the attribute, so for a property it runs that property's body, side effects and cost included. It returns False only when an AttributeError was caught; any other exception propagates. And if you need the value afterwards anyway, a single getattr(obj, name, default) is cheaper than hasattr plus a second lookup.

Examples

class A:
    x = 1
a = A()
print(hasattr(a,'x'))  # → True
print(hasattr(a,'y'))  # → False
print(hasattr([],'append'))  # → True
print(hasattr([],'nonexistent'))  # → False
print(hasattr('str','upper'))  # → True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy