ZetCode

Python __delete__ Method

Last modified November 17, 2026 Python 3.15

The __delete__ method is part of the descriptor protocol. When del obj.name targets an attribute that is a data descriptor on the class, Python calls the descriptor's __delete__ instead of touching the instance dictionary. This article explains when the hook runs, how it differs from __delattr__, and how to use it for protected fields and cache invalidation.

A descriptor that handles deletion

A descriptor is a class attribute that implements any of __get__, __set__, or __delete__. Defining __delete__ makes it a data descriptor, which takes precedence over the instance dictionary. The following Field stores its value per instance and clears it on deletion.

basic_descriptor.py
class Field:
    def __set_name__(self, owner, name):
        self.name = name

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return obj.__dict__.get(self.name, 0)

    def __set__(self, obj, value):
        obj.__dict__[self.name] = value

    def __delete__(self, obj):
        print(f"deleting {self.name}")
        obj.__dict__.pop(self.name, None)


class Model:
    score = Field()


m = Model()
m.score = 10
print(m.score)
del m.score
print(m.score)
print(m.__dict__)

__set_name__ records the attribute name when the class is created, so the descriptor does not need to hard-code it. The setter writes into the instance dictionary under that name, and the getter supplies a default of 0 when the entry is absent. Deletion removes the entry, after which the getter falls back to the default, and the final print shows an empty instance dictionary.

$ python basic_descriptor.py
10
deleting score
0
{}

When the descriptor has no __delete__

A descriptor that defines __set__ but not __delete__ is still a data descriptor, so the interpreter tries its deletion path and finds nothing. The result is an AttributeError whose message is the name of the missing hook, and the stored value remains untouched.

missing_delete.py
class ReadOnly:
    def __set_name__(self, owner, name):
        self.name = name

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return obj.__dict__.get(self.name, "default")

    def __set__(self, obj, value):
        obj.__dict__[self.name] = value


class Model:
    value = ReadOnly()


m = Model()
m.value = 5
print(m.value)

try:
    del m.value
except AttributeError as e:
    print(type(e).__name__, e)

print(m.value)

The deletion fails with AttributeError: __delete__, which is less descriptive than a custom message but tells you exactly which protocol piece is missing. The value is still 5 afterwards. If deletion should be possible, add __delete__; if it should be explicitly forbidden, add a hook that raises a clearer error, as the next section does.

$ python missing_delete.py
5
AttributeError __delete__
5

Refusing deletion

A descriptor can reject deletion by raising AttributeError before changing any state. This is how a required field stays present for the lifetime of its owner. The error type matters, because callers and tools expect attribute failures to use AttributeError.

protect.py
class Required:
    def __set_name__(self, owner, name):
        self.name = name

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return obj.__dict__[self.name]

    def __set__(self, obj, value):
        obj.__dict__[self.name] = value

    def __delete__(self, obj):
        raise AttributeError(f"{self.name} is required")


class User:
    email = Required()

    def __init__(self, email):
        self.email = email


u = User("alice@example.com")
print(u.email)

try:
    del u.email
except AttributeError as e:
    print(type(e).__name__, e)

print(u.email)

The descriptor's getter indexes the dictionary directly, so it would raise KeyError if the value were missing; refusing deletion guarantees that the key exists. The attempted deletion produces the custom message, and the email is unchanged. Note that the constructor's assignment also goes through __set__, which is why the instance dictionary is populated.

$ python protect.py
alice@example.com
AttributeError email is required
alice@example.com

Invalidating a cached property

Deletion is a natural way to invalidate a cached value. The descriptor below computes a result on first access, stores it in the instance dictionary, and removes it when the attribute is deleted. Because the descriptor defines __delete__, it is a data descriptor even though it has no __set__.

lazy_cache.py
class cached:
    def __init__(self, func):
        self.func = func
        self.name = func.__name__

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        if self.name not in obj.__dict__:
            print(f"computing {self.name}")
            obj.__dict__[self.name] = self.func(obj)
        return obj.__dict__[self.name]

    def __delete__(self, obj):
        print(f"invalidating {self.name}")
        obj.__dict__.pop(self.name, None)


class Report:
    def __init__(self, rows):
        self.rows = rows

    @cached
    def total(self):
        return sum(self.rows)


r = Report([1, 2, 3])
print(r.total)
print(r.total)
del r.total
print(r.total)

The first access computes the sum and caches it, so the second access prints no message. Deleting total removes the cached entry, and the next read recomputes it. The @cached syntax works because the class is a decorator: the function is replaced by a descriptor instance in the class body, and the descriptor's __get__ returns the computed value.

$ python lazy_cache.py
computing total
6
6
invalidating total
computing total
6

Non-data descriptors

A descriptor that implements only __get__ does not intercept deletion. The instance dictionary wins for reading and writing, and del obj.name simply removes the instance entry. The descriptor is visible again only after that entry is gone.

non_data.py
class Info:
    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return "from descriptor"


class Model:
    info = Info()


m = Model()
print(m.info)

m.__dict__["info"] = "from instance"
print(m.info)

del m.info
print(m.info)

try:
    del m.info
except AttributeError as e:
    print(type(e).__name__, e)

The instance value shadows the descriptor, and deleting it exposes the descriptor again rather than calling any hook. The second deletion has no instance entry to remove, so it raises the standard error. This precedence rule is the main difference between data and non-data descriptors.

$ python non_data.py
from descriptor
from instance
from descriptor
AttributeError 'Model' object has no attribute 'info'

Deleting the class attribute

del obj.name invokes the descriptor, but del Class.name does not. The latter removes the attribute from the class itself and is handled by the metaclass, not by __delete__. The descriptor receives no call at all.

class_level.py
class Field:
    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return "value"

    def __delete__(self, obj):
        print("instance deletion")


class Model:
    field = Field()


m = Model()
del Model.field
print("field in class:", "field" in Model.__dict__)

No message is printed, and the class no longer has the attribute. Existing instances lose access to the descriptor as well. This distinction matters when code is supposed to clean up a class-level registration: it must call the appropriate cleanup method rather than relying on the descriptor hook.

$ python class_level.py
field in class: False

Best practices

A deletion hook changes the meaning of an attribute, so document it with the rest of the descriptor:

Source

object.__delete__ - Python documentation

Implementing descriptors - Python documentation

Descriptor HowTo Guide - Python documentation

In this article we have implemented the __delete__ method. We have covered the descriptor deletion path, missing hooks, protected attributes, cache invalidation, non-data descriptor precedence, and class-level removal. For related topics, see Python __get__ method, Python __set__ method, Python __delattr__ method, and Python property built-in.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.