Sobes.tech
Junior — Middle

Can you explain the purpose of the __delete__() method in a Python descriptor and how it works?

sobes.tech AI

Answer from AI

The __delete__() method in a Python descriptor is responsible for deleting an attribute from the object to which the descriptor is applied.

A descriptor is an object that implements the __get__(), __set__(), and/or __delete__() methods, and manages access to attributes of another object.

When del instance.attr is called, if attr is a descriptor with a __delete__() method, this method is invoked with the argument instance — the object from which the attribute is being deleted.

Example:

class Descriptor:
    def __delete__(self, instance):
        print(f"Deleting attribute from {instance}")
        # Here you can implement deletion logic, for example, from a dictionary
        if hasattr(instance, '_value'):
            del instance._value

class MyClass:
    attr = Descriptor()

obj = MyClass()
del obj.attr  # calls Descriptor.__delete__(obj)

Thus, __delete__() allows controlling the behavior when an attribute is deleted, such as clearing related data or performing additional actions.