hasattr()
hasattr(object, name) bool · Updated March 13, 2026 · Built-in Functions The hasattr() function checks whether an object has a named attribute. It returns True if the attribute exists (either on the object itself or inherited from its class), and False if it doesn’t exist. This is useful for writing defensive code that checks for optional features before using them.
Syntax
hasattr(object, name)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
object | object | — | Any Python object (class, instance, module, etc.) |
name | str | — | The attribute name as a string |
Examples
Basic usage
class Person:
def __init__(self, name):
self.name = name
person = Person("Alice")
print(hasattr(person, "name"))
# True
print(hasattr(person, "age"))
# False
Checking for methods
text = "hello world"
print(hasattr(text, "upper"))
# True
print(hasattr(text, "not_a_method"))
# False
Checking for module attributes
import os
print(hasattr(os, "path"))
# True
print(hasattr(os, "nonexistent"))
# False
Common Patterns
Safe attribute access pattern
Use hasattr() together with getattr() to safely access attributes that may or may not exist:
def get_description(obj):
if hasattr(obj, "description"):
return getattr(obj, "description")
return "No description available"
Checking for optional features
def process_data(data):
# Check if data has certain methods before processing
if hasattr(data, "to_dict"):
data = data.to_dict()
if hasattr(data, "validate"):
data.validate()
return data
Dynamic feature detection
import sys
def check_python_version():
# Check if certain features are available
if hasattr(sys, "version_info"):
print(f"Python {sys.version_info.major}.{sys.version_info.minor}")
if hasattr(sys, "flags"):
print(f"Flags: {sys.flags}")
Class attribute checking
class Animal:
species = "Generic"
dog = Animal()
print(hasattr(dog, "species"))
# True
print(hasattr(dog, "breed"))
# False
print(hasattr(Animal, "species"))
# True
Errors
The hasattr() function itself does not raise exceptions—it always returns a boolean. However, the attribute name must be a string. Passing a non-string will raise a TypeError:
hasattr(person, 123)
# TypeError: hasattr(): attribute name must be string
Also note that hasattr() returns True even for attributes that raise exceptions when accessed (such as properties that always raise). This is because hasattr() only checks for existence, not whether accessing the attribute will succeed:
class Broken:
@property
def bad(self):
raise ValueError("This property always fails")
obj = Broken()
print(hasattr(obj, "bad"))
# True — attribute exists
print(obj.bad)
# ValueError: This property always fails
See Also
- built-in::getattr — get an attribute with optional default
- built-in::setattr — set an attribute on an object
- built-in::delattr — delete an attribute from an object
- built-in::vars — return the
__dict__of an object