Python delattr() Function


Python delattr() is a built-in function that deletes the named attribute of an object. delattr() does not return any value and deletes the attribute if object allows it.

Python delattr() function

Python delattr() Syntax

delattr(object,name)

As you can see in above syntax, Python delattr() takes two arguments:

  • object: object from which attribute will be removed. It is required.
  • name: It must be a string and also must be provided. It is the name of the attribute that is to be deleted or removed.

As we already mentioned delattr() doesn’t return any value, instead, it only deletes the mentioned attribute from the object provided that the object allows it.

delattr() is compatible with both versions Python 2.x and 3.x.

Python delattr() Function Example

How Python delattr() works?

Let’s just create a simple class and its object to demonstrate how delattr() works.

class Example:
   def __init__(self,a):
     self.a = a

#creating an object
obj = Example(5)
print(obj.a)

#Now removing attribute x
delattr(obj,'a')
print(obj.a)

Output

This will generate following output.

5
Traceback (most recent call last):
 File "<pyshell#5>", line 1, in <module>
 print(obj.a)
AttributeError: 'Example' object has no attribute 'a'

Explanation 

As you can see clearly,  delattr(obj, 'a'), removed attribute a from object obj. Hence it throws AttributeError when we try to access that removed attribute.