Skip to content

Python delattr() Function

How to remove object attributes in Python using the delattr() function, including syntax, parameters, and practical examples with error handling.

The delattr() function will delete the specified attribute from the specified object.

Syntax

delattr(object, name)

delattr() Parameters

Python delattr() function parameters:

Parameter Condition Description
object Required The object from which name attribute is to be removed
name Required The name of the attribute you want to remove

delattr() Return Value

Python delattr() function does not return any value (returns None). It only removes an attribute (if the object allows it).

Examples

How to use delattr() function

class Info:
    name = "TutorialReference"
    lang = "Python"
    site = "Google"

info_instance = Info()

print("Before deletion:", info_instance.lang)

delattr(Info, 'lang')

print("After deletion:", info_instance.lang)

output

Before deletion: Python
Traceback (most recent call last):
  File "main.py", line 16, in <module>
    print("After deletion:", info_instance.lang)
AttributeError: 'Info' object has no attribute 'lang'

Deleting attribute using del operator instead of delattr() function

You can also delete attribute of an object using del operator.

class Info:
    name = "TutorialReference"
    lang = "Python"
    site = "Google"

info_instance = Info()

print("Before deletion:", info_instance.lang)

del info_instance.lang

print("After deletion:", info_instance.lang)

output

Before deletion: Python
Traceback (most recent call last):
  File "main.py", line 16, in <module>
    print("After deletion:", info_instance.lang)
AttributeError: 'Info' object has no attribute 'lang'
Navigation