Python delattr() built-in function

From the Python 3 documentation

This is a relative of `setattr()`. The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it. For example, `delattr(x, 'foobar')` is equivalent to `del x.foobar`.

Introduction

The delattr() function in Python is used to delete an attribute from an object. It’s the counterpart to setattr() and getattr().

Syntax

delattr(object, name)
  • object: The object from which the attribute should be deleted.
  • name: The name of the attribute to delete, given as a string.

Examples

Deleting an attribute from an object

class Person:
    name = "John"
    age = 30

person = Person()
print(person.__dict__)  # Output: {'name': 'John', 'age': 30}
delattr(person, "age")
print(person.__dict__)  # Output: {'name': 'John'}

Deleting a non-existent attribute

class Person:
    name = "John"

person = Person()
try:
    delattr(person, "age")
except AttributeError as e:
    print(f"Error: {e}")

Subscribe to pythoncheatsheet.org

Join 16,702+ Python developers in a two times a month and bullshit free publication , full of interesting, relevant links.