hasattr()

The built-in hasattr() function allows you to check if an object has a specific attribute or method. It returns True if the attribute is present and False otherwise:

Python
>>> class Dog:
...     def bark(self):
...         print("Woof")
...

>>> pluto = Dog()
>>> hasattr(pluto, "bark")
True
>>> hasattr(pluto, "meow")
False

hasattr() Signature

Python Syntax
hasattr(object, name)

Arguments

Argument Description
object The object in which to look for the attribute or method.
name A string representing the name of the attribute to check.

Return Value

  • Returns True if the object has the specified attribute or method and False otherwise.

hasattr() Examples

With built-in classes:

Python
>>> hasattr(list, "append")
True
>>> hasattr(list, "put")
False

>>> hasattr(dict, "update")
True
>>> hasattr(dict, "next")
False

With an attribute name that exists in the object:

Python
>>> class Car:
...     def start(self):
...         print("Car started")
...

>>> car = Car()
>>> hasattr(car, "start")
True

With an attribute name that doesn’t exist in the object:

Python
>>> hasattr(car, "stop")
False

hasattr() Common Use Cases

The most common use cases for the hasattr() function include:

  • Checking for the existence of an attribute or method before using it to avoid errors.
  • Implement conditional logic based on available attributes or methods.

hasattr() Real-World Example

Consider a scenario where you have different types of vehicles, and you want to perform operations based on the available features:

Python cars.py
class Car:
    def start(self):
        print("Car started")

class Bicycle:
    def pedal(self):
        print("Pedaling bicycle")

# Usage
vehicles = [Car(), Bicycle()]

for vehicle in vehicles:
    if hasattr(vehicle, "start"):
        vehicle.start()
    elif hasattr(vehicle, "pedal"):
        vehicle.pedal()

In this example, hasattr() helps determine the available operation for each vehicle, allowing the code to execute the correct method without causing an error.

Tutorial

Duck Typing in Python: Writing Flexible and Decoupled Code

In this tutorial, you'll learn about duck typing in Python. It's a typing system based on objects' behaviors rather than on inheritance. By taking advantage of duck typing, you can create flexible and decoupled sets of Python classes that you can use together or individually.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 21, 2024 • Reviewed by Dan Bader