In Python, hasattr(obj, "name") returns True if obj.name can be read, and False otherwise. It finds instance attributes, class attributes, and methods alike.
It works by calling getattr() and checking whether that raises AttributeError. That makes it a natural tool for duck typing: checking what an object can do (“does it have read?”) instead of what type it is.
hasattr() is a built-in function: it lives in the builtins module, so it is always available without an import.
Syntax
Pass the object and the attribute name.
python
if hasattr(obj, "name"):
...
Call
What it does
hasattr("x", "upper")
Returns True.
hasattr(42, "upper")
Returns False.
hasattr(obj, "read")
Does it behave like a file?
hasattr(Class, "method")
Works on classes too.
If you are going to use the attribute right away, getattr(obj, "name", None) or try/except AttributeError avoids looking it up twice.
Library declarations
python
hasattr(object, name, /)
Parameters
Parameter
Description
object
Required. Any object.
name
Required. The attribute name as a string.
Return Value
Return Value
Description
bool
True if reading the attribute works.
Python Examples
Example 1 — Check Attributes and Methods
Test class attributes, methods, missing names, and built-in values.