Python delattr() Function

Spread the love

The delattr() function, as the name suggests, is used to delete attributes from an object. Attributes can be any named property of an object. It takes two parameters first is an object of the class and second is an attribute that we want to delete. For instance, if you have a class Person with an attribute age, you can use the delattr() function to remove the age attribute from an instance of the Person class.

Syntax and Parameters

The syntax for the delattr() function is:

delattr(object, name)
  • object: The object from which the attribute needs to be removed.
  • name: A string that specifies the name of the attribute to be deleted.

Return Value from delattr()

delattr( ) doesn’t return any value (returns None ). It only removes an attribute (if the object allows it).

How delattr() works?

In this example, we’re defining a simple class named Person. The class contains two attributes, name and age, initialized using the __init__ method.

class Person:
    def __init__(self, name, age): = name
        self.age = age

Next, an instance of the Person class named p is created with the name “Alice” and age 25.

p = Person("Alice", 25)

To visualize the attributes of this instance, we print the __dict__ attribute of p, which provides a dictionary representation of the instance’s namespace.

print(p.__dict__)  # Outputs: {'name': 'Alice', 'age': 25}

After this, we employ the delattr() function to delete the age attribute of the p object.

delattr(p, 'age')

Subsequently, when printing the __dict__ attribute of p again, we observe that the age attribute has been removed.

print(p.__dict__)  # Outputs: {'name': 'Alice'}

Conditional Deletion:

Sometimes, before removing an attribute from an object, it’s prudent to check if that attribute actually exists. This can prevent potential errors.

For this, we use the hasattr() function. It returns True if the object has the given attribute, and False otherwise.

if hasattr(p, 'age'):
    delattr(p, 'age')

In the code snippet above, before attempting to delete the age attribute using delattr(), we first verify its existence using hasattr(). If age exists in p, only then will the attribute be deleted.

This method is particularly beneficial when you’re not sure if an object has a specific attribute, thus helping avoid unnecessary AttributeError exceptions.

Deleting Attribute Using del Operator

The del keyword in Python is a versatile tool that can be used to delete various objects, including:

  • Variables
  • Items from a list
  • Attributes from an object
  • Items from a dictionary
  • And more…

When it comes to object attributes, the del keyword provides a direct way to remove an attribute from an instance of a class.

Using del to Delete Attributes

Consider the following example using the previously defined Person class:

class Person:
    def __init__(self, name, age): = name
        self.age = age

p = Person("Alice", 25)

To delete the age attribute from the p object, you can use the del keyword followed by the attribute reference:

del p.age

After executing the above line, the age attribute will no longer exist in the p object. If you try to access p.age afterwards, Python will raise an AttributeError indicating that the Person object has no attribute ‘age’.

Differences between delattr( ) and del

Static vs. Dynamic: The primary difference is that del requires you to know the attribute’s name at “design-time” (i.e., when you’re writing the code). In contrast, delattr() allows for dynamic deletion of attributes. This means you can determine the attribute’s name during “run-time” (i.e., when the code is being executed).

For instance, consider you want to delete an attribute based on some user input or a computation:

attribute_to_delete = input("Which attribute to delete?")
if hasattr(p, attribute_to_delete):
    delattr(p, attribute_to_delete)

Scope: While both del and delattr() can delete attributes, the del keyword has a broader scope. It can delete variables, list items, dictionary keys, etc. delattr(), on the other hand, is specifically designed for deleting attributes from objects.

Error Handling: With del, if you try to delete an attribute that doesn’t exist, you’ll get an AttributeError. With delattr(), the behavior is the same, but since it’s a function, you can more easily wrap it in a try-except block or combine it with functions like hasattr() to handle such scenarios gracefully.


The delattr() function in Python provides a powerful way to dynamically manage object attributes. While it’s an invaluable tool for advanced programming and dynamic attribute handling, it should be used judiciously to prevent unintended consequences. Always ensure that you’re deleting the right attributes and that these deletions won’t negatively impact other parts of your code.

Leave a Reply