In this article, we are going to see delattr() and del() functions in Python
delattr() in Python
The delattr() method is used to delete the named attribute from the object, with the prior permission of the object.
Syntax:
delattr(object, name): The function takes only two parameter:
- object: from which the name attribute is to be removed.
- name: of the attribute which is to be removed.
Return: The function doesn’t return any value.
The Working : Suppose we have a class by named Geek, and it has five students as the attribute. So, using the delattr() method, we can remove any one of the attributes.
Python3
class Geek: domain = "geeksforgeeks.org" if __name__ = = '__main__' : Lazyroar = Geek() print ( "Before deleting domain attribute from Lazyroar object:" ) print (Lazyroar.domain) delattr (Lazyroar, "domain" ) print ( "After deleting domain attribute from Lazyroar object:" ) # this will raise AttributeError if we try to access 'domain' attribute print (Lazyroar.domain) |
Output:
Traceback (most recent call last): File "02d61301-4399-4354-b3c3-86641ba21460.py", line 9, in <module> delattr(Lazyroar, "domain") AttributeError: domain
Explanation: The object of the class Geek is having one attribute named domain. If we use delattr() function on the Lazyroar object of the Geeks class for the domain attribute, then it’ll no more have the attribute domain. In that case, if we want to access the domain attribute, it will raise an AttributeError.
del operator in Python
There is another operator in Python that does the similar work as the delattr() method. It is the del operator. del operator makes some variable ready for garbage collection, if there is no reference of the variable in the later part of the program control flow.
Python3
class Geek: domain = "geeksforgeeks.org" if __name__ = = '__main__' : Lazyroar = Geek() print ( "Before deleting domain attribute from Lazyroar object:" ) print (Lazyroar.domain) # using del operator del Lazyroar.domain print ( "After deleting domain attribute from Lazyroar object:" ) # this will raise AttributeError if we try to access 'domain' attribute print (Lazyroar.domain) |
Output:
Before deleting domain attribute from Lazyroar object: geeksforgeeks.org Traceback (most recent call last): File "792e8f29-bcdc-4756-abc2-72b03b77540d.py", line 10, in <module> del Lazyroar.domain AttributeError: domain
delattr() and del() in Python
- Dynamic deletion : del is more explicit and efficient, and delattr() allows dynamic attribute deleting.
- Speed : If the above programs are considered and run, then there is a slight difference between the speed of execution. del is slightly faster in comparison to delattr(), depending on the machine.
- byte-code Instructions : del also takes less byte-code instructions in comparison to delattr().
So we conclude the comparison by saying that del is slightly faster than delattr, but when it comes to dynamic deletion of attributes then delattr() has an advantage as it is not possible by del operator.