Python delattr() Function – Delete Attribute from Object

Python delattr() Function

The delattr() function in Python is used to delete an attribute from an object. It’s useful when you want to dynamically remove properties from user-defined objects.

Syntax

delattr(object, name)

Parameters:

  • object – The object whose attribute you want to delete
  • name – A string representing the name of the attribute

Returns:

  • Nothing. It deletes the attribute in place.

Example 1: Deleting an Attribute from an Object

class Person:
    name = "Alice"
    age = 25

# Delete the 'age' attribute
delattr(Person, 'age')

# Now let's try to access it
p = Person()
print(hasattr(p, 'age'))
False

Example 2: With Object Instances

class Car:
    def __init__(self):
        self.color = "red"
        self.brand = "Toyota"

c = Car()
delattr(c, 'color')

print(hasattr(c, 'color'))
False

Use Case: When is delattr() Useful?

  • When you want to remove an attribute dynamically at runtime
  • Used in metaprogramming and frameworks that modify object structure
  • Cleaning up unnecessary attributes before serialization

Equivalent Code Using del

You can also delete attributes like this:

del object.attribute

But delattr() lets you use the attribute name as a string, which is helpful for dynamic situations.

Common Errors

  • AttributeError: If the attribute doesn't exist
  • TypeError: If the attribute name is not a string

Interview Tip

delattr() is handy in scenarios involving reflection, metaclasses, and frameworks like Django where models are modified dynamically.

Summary

  • delattr(object, "attr") removes the named attribute
  • Works like del obj.attr but uses a string name
  • Raises AttributeError if the attribute doesn’t exist

Practice Problem

Create a class Student with attributes name and grade. Delete the grade attribute using delattr() and print whether the attribute still exists.

class Student:
    def __init__(self):
        self.name = "Bob"
        self.grade = "A"

s = Student()
delattr(s, 'grade')
print(hasattr(s, 'grade'))

Expected Output:

False