delattr()

The built-in delattr() function allows you to delete attributes from objects in Python, particularly when the attribute names are determined at runtime. The function’s primary purpose is to remove an attribute from an object given its name as a string:

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

>>> jane = Person("Jane", 30)
>>> delattr(jane, "age")
>>> jane.age
Traceback (most recent call last):
    ...
AttributeError: 'Person' object has no attribute 'age'

delattr() Signature

Python Syntax
delattr(object, name)

Arguments

Argument Description
object The object from which you want to delete an attribute
name The name of the attribute to delete as a string

Return Value

  • Deletes the specified attribute from the input object.

delattr() Examples

With a class instance and attribute name as arguments:

Python
>>> class Car:
...     def __init__(self, model, year):
...         self.model = model
...         self.year = year
...

>>> car = Car("Toyota", 2020)
>>> delattr(car, "year")
>>> car.year
Traceback (most recent call last):
    ...
AttributeError: 'Car' object has no attribute 'year'

delattr() Common Use Cases

The most common use cases for the delattr() function include:

  • Dynamically deleting attributes of objects when attribute names are only known at runtime.
  • Managing object attributes in frameworks or applications that require dynamic attribute manipulation.

delattr() Real-World Example

Imagine a scenario where you have a configuration object with optional attributes, and you need to clean it up by removing certain attributes at runtime:

Python
>>> class Config:
...     def __init__(self, **kwargs):
...         for key, value in kwargs.items():
...             setattr(self, key, value)
...

>>> config = Config(debug=True, version="1.0", obsolete=True)
>>> delattr(config, "obsolete")
>>> hasattr(config, "obsolete")
False

In this example, delattr() helps you remove the obsolete attribute from the config object, allowing for cleaner and more efficient configuration management.

delattr() in Custom Classes

To prevent attribute deletion in custom classes, you can override the .__delattr__() method. Here’s how you can do it:

Python non_deletable.py
class NonDeletable:
    def __init__(self, value):
        self.value = value

    def __delattr__(self, name):
        raise AttributeError(
            f"{type(self).__name__} object doesn't "
            f"support attribute deletion"
        )

# Usage
one = NonDeletable(1)
print(one.value)  # Output: 1

del one.value 
# Raises an AttributeError exception:
# NonDeletable object doesn't support attribute deletion

In this example, the .__delattr__() method is overridden to raise an AttributeError exception if an attempt is made to delete any attribute, effectively preventing attribute deletion.

Related Resources

Tutorial

Object-Oriented Programming (OOP) in Python

In this tutorial, you'll learn all about object-oriented programming (OOP) in Python. You'll learn the basics of the OOP paradigm and cover concepts like classes and inheritance. You'll also see how to instantiate an object from a class.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 12, 2024 • Reviewed by Dan Bader