delattr() Builtin Function

Python – delattr()

Python delattr() builtin function deletes specified property from the given object.

Syntax

The syntax of delattr() function is

delattr(object, attribute)

where

  • object is a Python object from which we delete the property.
  • attribute is the name of the property.

Examples

Delete attribute from object

In the following program, we define a Fruit class with three attributes: name, quantity, and description. We create an object of this Fruit type, and delete the description attribute using delattr() function.

Python Program

class Fruit:
    name = ''
    quantity = ''
    description = ''
    
    def __init__(self, name, quantity, description):
        self.name = name
        self.quantity = quantity
        self.description = description

    def __str__(self):
        details = ''
        details += f'Name        : {self.name}\n'
        details += f'Quantity    : {self.quantity}\n'
        details += f'Description : {self.description}\n'
        return details

apple = Fruit('Apple', '58', 'Good for health.')

#before delete attribute
print(apple)

delattr(apple, 'description')
#after delete attribute
print(apple)
Run

Output

Name        : Apple
Quantity    : 58
Description : Good for health.

Name        : Apple
Quantity    : 58
Description : 

Delete attribute (which is not present) from object

If we try to delete an attribute that is not present in the object, then the interpreter raises AttributeError.

In the following program, we delete an attribute named 'someother' which is not present for the apple object. Therefore python interpreter raises AttributeError.

Python Program

class Fruit:
    name = ''
    quantity = ''
    description = ''
    
    def __init__(self, name, quantity, description):
        self.name = name
        self.quantity = quantity
        self.description = description

    def __str__(self):
        details = ''
        details += f'Name        : {self.name}\n'
        details += f'Quantity    : {self.quantity}\n'
        details += f'Description : {self.description}\n'
        return details

apple = Fruit('Apple', '58', 'Good for health.')

#before delete attribute
print(apple)

delattr(apple, 'someother')
#after delete attribute
print(apple)
Run

Output

Name        : Apple
Quantity    : 58
Description : Good for health.

Traceback (most recent call last):
  File "/Users/arjun/Documents/workspace/python/selenium/example1.py", line 23, in <module>
    delattr(apple, 'someother')
AttributeError: someother

Summary

In this tutorial of Python Examples, we learned the syntax of delattr() function, and how to delete an attribute from an object, with examples.