Python delattr()

Python delattr() allows you to remove an attribute from an object. You can think of attributes like variables that belong to an object, holding data specific to that object. Python delattr() provides a way to delete these attributes dynamically, using the attribute's name as a string.
Table of Contents

Understanding Python delattr() Function

Python delattr() function is a built-in function that allows you to delete an attribute from an object. Attributes are data stored within an object, like variables belonging to a specific instance or class. Python delattr() takes two arguments: the object from which you want to delete the attribute and the name of the attribute you want to delete (as a string). This function is useful when you must dynamically remove attributes from objects during runtime based on certain conditions or logic in your program.

Syntax of Python delattr()

delattr(object, attribute_name)

Explanation

  • delattr(): Built-in function that deletes the specified attribute.
  • object: Object from which you want to delete the attribute. It is passed as first parameter to delattr().
  • attribute_name: String representing the name of the attribute to be deleted. It is passed as second parameter to delattr().

Example of Python delattr()

class MyClass:
    def __init__(self, x, y):
        self.x = x
        self.y = y

obj = MyClass(10, 20)
print(obj.x)
delattr(obj, "x")
print(hasattr(obj, "x"))

Explanation

  • class MyClass:: Defines a class named MyClass.
  • def __init__(self, x, y):: Constructor for MyClass, taking x and y as arguments.
  • self.x = x: Initializes an attribute x with the value of x.
  • self.y = y: Initializes an attribute y with the value of y.
  • obj = MyClass(10, 20): Creates an object obj of MyClass with x set to 10 and y set to 20.
  • print(obj.x): Prints the value of attribute x of obj.
  • delattr(obj, "x"): Deletes the attribute x from obj using delattr().
  • print(hasattr(obj, "x")): Checks if obj still has an attribute x and prints the result.

Output

10
False


delattr() Parameters

Python delattr() function takes two parameters: the first is the object from which you want to remove an attribute, and the second is the name of the attribute you wish to remove, given as a string. The second parameter must be a string matching the attribute’s name. If the attribute doesn’t exist in the object, delattr() will raise an AttributeError.

Syntax

delattr(object, attribute_name)

Example

class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.name)
delattr(my_dog, "name")
print(hasattr(my_dog, "name"))

Explanation

  • class Dog:: Defines a class named Dog.
  • def __init__(self, name, breed):: Constructor for Dog, accepting name and breed as parameters.
  • self.name = name: Initializes the name attribute with the provided value.
  • self.breed = breed: Initializes the breed attribute.
  • my_dog = Dog("Buddy", "Golden Retriever"): Creates a Dog object named my_dog.
  • print(my_dog.name): Prints the name attribute of my_dog.
  • delattr(my_dog, "name"): Deletes the name attribute from my_dog using delattr().
  • print(hasattr(my_dog, "name")): This checks if my_dog has a name attribute and prints the result.

Output

Buddy
False


delattr() Return Value

Python delattr() function does not return any value. It modifies the object in place by removing the specified attribute directly from the object. If the attribute exists and is successfully deleted, delattr() completes silently. If the attribute does not exist, delattr() raises an AttributeError. Therefore, you don’t typically use delattr() to get a value but rather to perform an action (deleting an attribute).

Example

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("Alice", 30)
print(person.age)
delattr(person, "age")
print(hasattr(person, "age"))

Explanation

  • class Person:: Defines a class named Person.
  • def __init__(self, name, age):: Constructor for Person.
  • self.name = name: Initializes the name attribute.
  • self.age = age: Initializes the age attribute.
  • person = Person("Alice", 30): Creates a Person object named person.
  • print(person.age): Prints the age attribute of person.
  • delattr(person, "age"): Deletes the age attribute from person using delattr().
  • print(hasattr(person, "age")): Checks if person still has an age attribute and prints the result.

Output

30
False


Deleting Attribute Using del Operator

In Python, you can delete an attribute from an object using the del operator, which is a more direct way than using Python delattr(). You write del, followed by the object name, a dot (.), and the attribute name. This statement directly removes the attribute from the object. If the attribute doesn’t exist, Python will raise an AttributeError.

Syntax

del object.attribute_name

Explanation

  • del: Keyword used to delete an attribute from an object.
  • object: Object from which you want to delete the attribute.
  • attribute_name: Name of the attribute you want to delete. You don’t need to pass it as string here unlike delattr().

Example

class Car:
    def __init__(self, make, model):
        self.make = make
        self.model = model

my_car = Car("Toyota", "Camry")
print(my_car.make)
del my_car.make
print(hasattr(my_car, "make"))

Explanation

  • class Car:: Defines a class named Car.
  • def __init__(self, make, model):: Constructor for Car.
  • self.make = make: Initializes the make attribute.
  • self.model = model: Initializes the model attribute.
  • my_car = Car("Toyota", "Camry"): Creates a Car object named my_car.
  • print(my_car.make): Prints the make attribute of my_car.
  • del my_car.make: Deletes the make attribute from my_car using del operator.
  • print(hasattr(my_car, "make")): Checks if my_car has a make attribute and prints the result.

Output

Toyota
False


Conclusion

Python delattr() function allows dynamically removing attributes from objects by specifying the attribute’s name as a string. While the del operator offers a more direct approach for deleting attributes, Python delattr is particularly useful when deleting attributes based on dynamically determined names or when working with strings representing attribute names. Understanding how to use delattr() and del effectively allows you to manage object attributes more flexibly during program execution, which can be necessary for specific advanced programming patterns. Remember that delattr() will raise AttributeError if the specified attribute does not exist in the object.


Also Read

Python complex()

Python dict()


Python Reference

python delattr()

Table of Contents