Python hasattr()

Python hasattr() function is a simple yet powerful tool for checking the presence of attributes or methods in an object. It is particularly useful in dynamic programming scenarios where the structure of objects may not be known in advance. Using hasattr(), you can write more robust and flexible code that adapts to different situations.
Table of Contents

Understanding Python hasattr() Function

Python hasattr() is a built-in function that checks if an object has a specified attribute. It takes two arguments: the object you want to inspect and the name of the attribute you’re looking for (as a string). Python hasattr() returns True if the object has an attribute with that name, and False otherwise. This function is useful when you need to determine if an object has a particular attribute or method before trying to access it, helping you avoid AttributeError exceptions.

Syntax of Python hasattr()

has_attribute = hasattr(object, attribute_name)

Explanation

  • has_attribute: Variable will store the boolean result returned by hasattr().
  • hasattr(): Built-in function that checks for the attribute’s existence.
  • object: Object you’re inspecting for the attribute. It is passed as first parameter to hasattr().
  • attribute_name: String representing the name of the attribute you’re checking for. It is passed as second parameter to hasattr().

Syntax of Python hasattr()

class MyClass:
    def __init__(self, x):
        self.x = x

obj = MyClass(10)
print(hasattr(obj, 'x'))
print(hasattr(obj, 'y'))

Explanation

  • class MyClass:: Defines a class named MyClass.
  • def __init__(self, x):: Constructor for MyClass.
  • self.x = x: Initializes attribute x.
  • obj = MyClass(10): Creates an instance of MyClass.
  • print(hasattr(obj, 'x')): Checks if obj has an attribute named ‘x’ and prints the result.
  • print(hasattr(obj, 'y')): Checks if obj has an attribute named ‘y’ and prints the result.

Output

True
False


hasattr() Parameters

Python hasattr() function takes two parameters: object and attribute_name. The object parameter is the object you want to check for the existence of an attribute. The attribute_name parameter is a string representing the name of the attribute you’re looking for. Attribute_name must be a string; otherwise, hasattr() will raise a TypeError.

Syntax

result = hasattr(object, attribute_name)

Example

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

dog = Dog("Rover")
print(hasattr(dog, "name"))
print(hasattr(dog, "age"))

Explanation

  • class Dog:: Defines a class named Dog.
  • def __init__(self, name):: Constructor for Dog.
  • self.name = name: Initializes the name attribute.
  • dog = Dog("Rover"): Creates a Dog object.
  • print(hasattr(dog, "name")): Checks if dog has a name attribute and prints the result.
  • print(hasattr(dog, "age")): Checks if dog has an age attribute and prints the result.

Output

True
False


hasattr() Return Value

Python hasattr() function returns a boolean value: True or False. It returns True if the specified object has an attribute with the given name, and False otherwise. It’s important to note that hasattr() doesn’t distinguish between attributes and methods; it simply checks if a name exists in the object’s namespace.

Syntax

boolean_result = hasattr(object, attribute_name)

Explanation

  • boolean_result: Variable will store the boolean value (True or False) returned by hasattr().
  • hasattr(): Function returns True if the attribute exists, False otherwise.
  • object: Object being checked. It is passed as first parameter to hasattr().
  • attribute_name: Name of the attribute, as a string. It is passed as second parameter to hasattr().

Example

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

    def meow(self):
        pass

cat = Cat("Whiskers")
print(hasattr(cat, "meow"))

Explanation

  • class Cat:: Defines a class named Cat.
  • def __init__(self, name):: Constructor for Cat.
  • self.name = name: Initializes the name attribute.
  • def meow(self):: Defines a method meow.
  • pass: Indicates that meow has no implementation here.
  • cat = Cat("Whiskers"): Creates a Cat object.
  • print(hasattr(cat, "meow")): Checks if cat has a method named meow and prints the result.

Output

True


Python hasattr() with Methods

You can use Python hasattr() to check if an object has a specific method. Since methods are essentially callable attributes, hasattr() works for methods like regular attributes. You pass the object and the method’s name as a string to hasattr(), which returns True if the object has that method and False otherwise.

Syntax

has_method = hasattr(object, method_name)

Explanation

  • has_method: Variable will store the boolean result indicating whether the object has the method.
  • hasattr(): Function checks for the existence of the method.
  • object: Object you’re checking. It is passed as first parameter to hasattr().
  • method_name: Name of the method you’re looking for, as a string. It is passed as second parameter to hasattr().

Example

class MyClass:
    def my_method(self):
        pass

obj = MyClass()
print(hasattr(obj, "my_method"))

Explanation

  • class MyClass:: Defines a class named MyClass.
  • def my_method(self):: Defines a method named my_method.
  • pass: Indicates that my_method doesn’t do anything here.
  • obj = MyClass(): Creates an instance of MyClass.
  • print(hasattr(obj, "my_method")): Checks if obj has a method named my_method and prints the result.

Output

True


Handling Different Object Types with Python hasattr()

One of the useful applications of Python hasattr() is in flexibly handling different object types. You can use hasattr() to check if an object has certain attributes or methods before you try to access or call them. This allows you to write code that can work with various objects, even if they don’t share the same interface or inheritance hierarchy.

Syntax

if hasattr(object, attribute_or_method_name):
    # Do something with object.attribute_or_method_name

Explanation

  • if hasattr(object, attribute_or_method_name):: Checks if object has an attribute or method named attribute_or_method_name.
  • hasattr(): Function performs the check.
  • object: Object you’re inspecting. It is passed as first parameter to hasattr().
  • attribute_or_method_name: Name of the attribute or method, as a string. It is passed as second parameter to hasattr().
  • # Do something with object.attribute_or_method_name: Where you’d write code that uses the attribute or method, now that you know it exists.

Example

class Dog:
    def bark(self):
        print("Woof!")

class Cat:
    def meow(self):
        print("Meow!")

def make_sound(animal):
    if hasattr(animal, "bark"):
        animal.bark()
    elif hasattr(animal, "meow"):
        animal.meow()

dog = Dog()
cat = Cat()

make_sound(dog)
make_sound(cat)

Explanation

  • class Dog:: Defines a class named Dog.
  • def bark(self):: Defines a method bark for Dog.
  • print("Woof!"): Prints “Woof!” when bark is called.
  • class Cat:: Defines a class named Cat.
  • def meow(self):: Defines a method meow for Cat.
  • print("Meow!"): Prints “Meow!” when meow is called.
  • def make_sound(animal):: Defines a function make_sound that takes an animal object.
  • if hasattr(animal, "bark"):: Checks if the animal has a bark method.
  • animal.bark(): Calls bark if it exists.
  • elif hasattr(animal, "meow"):: Checks if the animal has a meow method.
  • animal.meow(): Calls meow if it exists.
  • dog = Dog(): Creates a Dog object.
  • cat = Cat(): Creates a Cat object.
  • make_sound(dog): Calls make_sound with the dog object.
  • make_sound(cat): Calls make_sound with the cat object.

Output

Woof!
Meow!


Conclusion

Python hasattr() is a simple yet powerful function for checking the existence of attributes or methods in objects. It helps you write more robust and flexible code that can handle different object types and dynamically adapt to the presence or absence of certain attributes. By using Python hasattr to test for an attribute before trying to access it, you can avoid AttributeError exceptions and make your code more resilient to changes.


Also Read

Python exec()

Python help()


Python Reference

python hasattr()

Table of Contents