How to Check if Python Object Has Attribute (3 Ways)

Check if an object has a certain attribute in Python

Learn how to check if an object has a specific attribute in Python using hasattr(), getattr(), and try-except. This guide includes easy explanations, real-life analogies, code examples, and best practices for beginners

Checking if an Object Has an Attribute in Python

The primary method to check if an object has an attribute in Python is the built-in hasattr() function. Other approaches include using getattr() with a default value and using try-except blocks. These methods help prevent errors like AttributeError and make your code more reliable.

By the end of this article, you will know three main ways to check for attributes, when to use each, and how to write Python code safely.

What Are Attributes and Objects in Python?

In Python:

  • Object: An instance of a class that holds data and behavior.
  • Attribute: A property or characteristic of an object, like color, name, or age.

Attributes can store data values or methods. Before accessing an attribute, it’s good practice to check whether it exists. This avoids runtime errors and keeps your programs smooth.

3 Simple Ways to Check if an Object Has an Attribute in Python

1. Check Using hasattr()

hasattr() is the simplest and most common method. It checks if an object has a specific attribute and returns True or False.
Think of it like checking if a car has wheels. If that property exist, the hasattr() will return true, and if the attribute does not exist, the function will return false. So, using hasattr(), you can find out whether an object has a specific attribute or not.

hasattr() working in python to check for attributes

Syntax

hasattr(object, attribute_name)
  • object: The object you want to check.
  • attribute_name: The name of the attribute you want to check, written as a string.

The function returns True if the object has the attribute, and False otherwise.

Example

The code defines a Car class with wheels and color attributes, then creates a toy_car instance with 4 wheels and color red. Next, hasattr() checks whether specific attributes exist. For wheels it returns True, and for sunroof it returns False since it isn’t defined. This is how hasattr() efficiently checks for attribute presence.

# Define the Car class with attributes wheels and color
class Car:
    def __init__(self, wheels, color):
        self.wheels = wheels
        self.color = color

# Create an instance of Car with 4 wheels and color red
toy_car = Car(wheels=4, color='red')

# Check if the car has the attribute 'wheels' and 'sunroof'
has_wheels = hasattr(toy_car, 'wheels')
has_sunroof = hasattr(toy_car, 'sunroof')

# Output the return values of hasattr()
print("Wheels: ", has_wheels)  # Expected output: True
print("Sunroof: ", has_sunroof)  # Expected output: False

Output

Wheels: True
Sunroof: False

2. Check Using a try-except Block

This method aligns with Python’s EAFP principle: “Easier to Ask Forgiveness than Permission”. It means you try to access the attribute directly and catch the error if it doesn’t exist. For more details, check our guide on handling Python errors.

Syntax

try:
    # Attempt to access an attribute
except AttributeError:
    # This code runs if the attribute is missing
  • try block: Place the code where you attempt to access the attribute.
  • except AttributeError block: Specify what should happen if the attribute does not exist.

Example

Here, try and except blocks handle potential errors when accessing car attributes. First, accessing wheels succeeds since it exists — no error occurs. Then, accessing sunroof raises an AttributeError since it isn’t defined. The except block catches this error and prints a message, allowing the program to continue running smoothly.

# Define the Car class with attributes wheels and color
class Car:
    def __init__(self, wheels, color):
        self.wheels = wheels
        self.color = color

# Create an instance of Car with 4 wheels and color red
toy_car = Car(wheels=4, color='red')

# Try to access the 'wheels' attribute
try:
    print(f"Wheels: {toy_car.wheels}")  # This will work as 'wheels' attribute exists
except AttributeError:
    print("The car has no wheels.")

# Try to access the 'sunroof' attribute
try:
    print(f"Sunroof: {toy_car.sunroof}")  # This will raise an AttributeError
except AttributeError:
    print("The car has no sunroof.")

Output

Wheels: 4
The car has no sunroof.

Once you find out if an object has attributes, you may want to print all properties of attributes of that object.

3. Check Using getattr() With a Default Value

In Python, getattr() retrieves an attribute’s value from an object. If the attribute doesn’t exist, it either returns a default value or raises an error. Think of it like checking if a car has wheels, if it does, it returns 4. Otherwise, it returns a default like 'The car has no wheels' or raises an error.

getattr() working in python to check for attributes

Syntax

getattr(object, attribute_name[, default])
  • object: The object from which you want to access the attribute.
  • attribute_name: The name of the attribute you want to check, written as a string.
  • default (optional): A value returned if the attribute isn’t found. If omitted and the attribute is missing, getattr() raises an AttributeError — triggered when accessing an attribute that doesn’t exist on an object.

Example

Here, getattr() retrieves the wheels attribute from toy_car, returning 4 since it exists. Then, getattr() checks for sunroof, which doesn’t exist — so it returns the default value 'The car has no sunroof'. This shows how getattr() accesses existing attributes and provides a fallback when one is missing.”

# Define the Car class with attributes wheels and color
class Car:
    def __init__(self, wheels, color):
        self.wheels = wheels
        self.color = color

# Create an instance of Car with 4 wheels and color red
toy_car = Car(wheels=4, color='red')

# Use getattr() to check if the car has wheels attribute
# If the attribute doesn't exist, it will return "The car has no wheels"
wheels = getattr(toy_car, 'wheels', "The car has no wheels")
print(f"Wheels: {wheels}")

# Use getattr() to check if the car has a sunroof attribute (which doesn't exist)
# Since sunroof is not defined, it will return "The car has no sunroof"
sunroof = getattr(toy_car, 'sunroof', "The car has no sunroof")
print(f"Sunroof: {sunroof}")

Output

Wheels: 4
Sunroof: The car has no sunroof

Quick Comparison of Methods

MethodChecks AttributeReturns ValueHandles MissingUse Case
hasattr()YesBooleanNoQuick existence check
try-exceptYesValueYesWhen attribute mostly exists, EAFP style
getattr()YesValue/DefaultYesRetrieve attribute with fallback

Why Checking Attributes Matters

  • Avoid Errors: Prevents crashes like AttributeError.
  • Handle Missing Data: Allows fallback values or alternative actions.
  • Improves Reliability: Makes your code predictable.
  • Control Program Flow: Decide what to do if attributes are present or missing.
  • Enhances User Experience: Gives meaningful messages instead of abrupt failures.

Best Practices

You can use:

  • hasattr() for simple checks.
  • getattr() with a default when you want the value safely.
  • try-except for EAFP style, especially when attributes mostly exist.
  • Avoid checking private attributes (those starting with _) unless necessary.

Practice in Our Python Compiler

Try these examples yourself in our online Python compiler to see how hasattr(), getattr(), and try-except work in real-time. Experimenting helps you understand attribute checking better and prevents common mistakes.

Conclusion

Checking if an object has an attribute helps you avoid errors and write better Python code. By using methods like hasattr()getattr()try blocks, dir()__dict__, and vars(), you can make sure that attributes are present before you try to use them. This practice leads to code that is less likely to crash and easier to understand. It also helps in debugging and ensures that your programs work smoothly with different objects. Overall, these techniques make your code more reliable and maintainable.

FAQs

1. What is the difference between hasattr() and getattr()?

hasattr() checks if the attribute exists and returns True or False. getattr() returns the attribute value or a default if missing. Use hasattr() for checks and getattr() for safe access.

2. Can I check nested attributes in Python?

Yes. You can chain getattr(), e.g., getattr(obj, 'attr1', {}).get('attr2', default) for nested attributes.

3. What happens if I try to access an attribute that doesn’t exist?

Python raises an AttributeError. Using hasattr(), getattr() with default, or try-except prevents this.

4. Are there other ways to list all attributes of an object?

Yes. Use dir(object) for all attributes/methods or object.__dict__ for instance-specific attributes.

Scroll to Top