89DEVs

Python delattr() function

The delattr() function deletes an attribute from a given object if it is allowed to delete the attribute. Attributes can also be deleted by using the del operator. 


# create Class and check attributes
class Dog:
   name = 'Mikey'
   age = 5
   breed = 'husky'

mikey = Dog()
print(dir(mikey))


We can use the dir() function to return a list of all valid attributes. Like expected 'age', 'breed' and 'name' are valid attributes.


['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'breed', 'name']


Delete attribute with delattr()

We can use the delattr() function to delete the breed attribute. # delete attribute using delattr() class Dog: name = 'Mikey' age = 5 breed = 'husky' mikey = Dog() delattr(Dog, 'breed') print(dir(mikey)) We deleted the breed attribute and it's not showing anymore in the attribute list. ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name']

Delete attributes using del operator

Alternatively, we can delete the attribute with the del operator. # delete attribute using del operator class Dog: name = 'Mikey' age = 5 breed = 'husky' mikey = Dog() del Dog.breed print(dir(mikey)) The attribute 'breed' is deleted and the same list of attributes, without the breed is returned. ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name']

delattr() syntax

The syntax of delattr() is: delattr(object, attribute_name)

delattr() arguments

The delattr() functions accepts exactly 2 arguments:
  • required: object, the given object to remove the attribute from
  • required: attribute_name, the attribute name to remove from the object
If more or less than two arguments are given, a TypeError exception is raised. If the attribute doesn't exist, an AttributeError is raised. TypeError: delattr expected 2 arguments, got 1

delattr() return value

The delattr() function returns None.

related functions

The dir() function can be used to print all existing attributes of an object. The hasattr() function can be used to check if a specific attribute exists.

                
        

Summary


Click to jump to section