Python hasattr() – Easy Examples and Use Cases

Python’s built-in hasattr(object, string) function takes an object and a string as an input. It returns True if one of the object‘s attributes has the name given by the string. Otherwise, it returns False.

Syntax hasattr()

The hasattr() object has the following syntax:

Syntax: 
hasattr(object, attribute)         # Does the object have this attribute?
ArgumentsobjectThe object from which the attribute value should be drawn.
attributeThe attribute name as a string.
Return ValueobjectReturns Boolean whether the attribute string is the name of one of the object‘s attributes.

The hasattr(object, attribute) method returns True, if the object has the attribute and False otherwise.

Example Usage

Learn by example! Here’s an example on how to use the hasattr() built-in function.

# Define class with one attribute
class Car:
    def __init__(self, brand):
        self.brand = brand


# Create object
porsche = Car('porsche')

# Check if porsche has attributes
print('Porsche has attribute "brand": ', hasattr(porsche, 'brand'))
print('Porsche has attribute "color": ', hasattr(porsche, 'color'))

The output of this code snippet is:

Porsche has attribute "brand":  True
Porsche has attribute "color":  False

It has the attribute “brand” but not the attribute “color”.

Video hasattr()

Why? Nine Practical Use Cases of Python’s hasattr() Function

  1. Error Handling: You can use hasattr() to avoid accessing errors when trying to access an attribute of a dynamic object.
  2. Ternary Operator: You can use hasattr() in a ternary operator to conditionally assign a value to a variable such as in: age = object.age if hasattr(object, 'age') else 0. However, be careful when using hasattr() as it always return False, no matter the error message. Thus, it may overshadow an error different to the error that appears if the attribute doesn’t exist. So, the attribute may indeed exist but if trying to access it causes an error, the result will be False.
  3. Dynamic Attribute Access: Checking if an object has a certain attribute dynamically, useful in cases where attribute names are determined at runtime.
  4. Preventing Runtime Errors: Avoiding AttributeError by checking for attribute existence before attempting to access it.
  5. Custom Error Handling: Implementing custom error handling or logging when an expected attribute is missing from an object.
  6. Adaptive Code Execution: Adapting code behavior based on the presence or absence of certain attributes in objects.
  7. Feature Detection: Detecting if a particular feature or method is available in an object, especially useful when working with third-party libraries or APIs.
  8. Attribute-based Dispatch: Dispatching to different code paths based on which attributes an object has or lacks.
  9. Introspection and Debugging: Inspecting objects during debugging to understand their capabilities or to generate informative debug outputs.

Frequently Asked Questions (FAQs)

How Does hasattr() Function Check Attributes in Object’s Class and Its Superclasses?

The hasattr() function in Python is used to determine whether an object has a named attribute. It takes two arguments: the object and a string representing the name of the attribute you are checking for.

Here’s how the process works:

  1. Local Attributes Check: Initially, hasattr() checks whether the specified attribute name exists in the namespace of the object itself.
  2. Inheritance Check (Including Superclasses): If the attribute is not found in the local namespace, hasattr() will proceed to check in the namespaces of any superclasses from which the object’s class inherits, following the method resolution order (MRO). This way, it can detect attributes inherited from superclasses.
  3. Descriptor Protocol: If the class has defined __getattr__() or __getattribute__() methods, these methods are invoked as part of the attribute lookup process. If these methods raise an AttributeError, hasattr() will return False; otherwise, it will return True.

In essence, hasattr() provides a comprehensive check for attribute presence, encompassing both the local class namespace and inherited namespaces from superclasses.

This behavior ensures that hasattr() can accurately reflect the attribute lookup process that Python would perform during regular attribute access, making it a reliable tool for introspective operations in your code.

If you want to learn more about namespaces, feel free to read our tutorial and watch the associated video:

πŸ§‘β€πŸ’» Recommended: Understanding Namespaces in Python

What is the hasattr() function used for in Python?

The hasattr() function is handy for checking if a particular object has a given named attribute before attempting to access it. This can prevent runtime errors that would occur if you tried to access an attribute that doesn’t exist. Here’s how you’d use it:

class Dog:
    def __init__(self, name):
        self.name = name

fido = Dog('Fido')

# Check if fido has a 'name' attribute
print(hasattr(fido, 'name'))  # Output: True

# Check if fido has a 'bark' attribute
print(hasattr(fido, 'bark'))  # Output: False

How does hasattr() differ from getattr()?

While hasattr() checks if an object has a certain attribute, getattr() attempts to retrieve the value of that attribute. If the attribute doesn’t exist, getattr() will raise an AttributeError, unless a default value is provided as a third argument. Here’s a comparison:

class Cat:
    def __init__(self, name):
        self.name = name

whiskers = Cat('Whiskers')

# Using hasattr()
print(hasattr(whiskers, 'name'))  # Output: True
print(hasattr(whiskers, 'meow'))  # Output: False

# Using getattr()
print(getattr(whiskers, 'name'))  # Output: 'Whiskers'
print(getattr(whiskers, 'meow', 'default_value'))  # Output: 'default_value'

Can hasattr() check for method existence?

Absolutely! hasattr() can be used to check if an object has a specific method. Methods are just attributes that are callable. Here’s a simple example:

class Bird:
    def chirp(self):
        print('Chirp chirp!')

tweety = Bird()

# Check if tweety has a 'chirp' method
print(hasattr(tweety, 'chirp'))  # Output: True

What happens with hasattr() if an attribute is set to None?

Even if an attribute is set to None, hasattr() will still return True, as the attribute does exist on the objectβ€”it just has a value of None. Here’s an illustration:

class Fish:
    def __init__(self, name=None):
        self.name = name

nemo = Fish()

# Check if nemo has a 'name' attribute
print(hasattr(nemo, 'name'))  # Output: True

Related Functions

  • The getattr() function returns the value of an attribute.
  • The setattr() function changes the value of an attribute.
  • The hasattr() function checks if an attribute exists.
  • The delattr() function deletes an existing attribute.

Summary

Python’s built-in hasattr(object, string) function takes an object and a string as an input.

  • It returns True if one of the object‘s attributes has the name given by string.
  • It returns False otherwise if one of the object‘s attributes doesn’t have the name given by string.
>>> hasattr('hello', 'count')
True
>>> hasattr('hello', 'xxx')
False

Note that hasattr() also returns True if the string is the name of a method rather than an attribute.


I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:

Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!