How would you write a descriptor supporting attribute DELETION via __delete__, and what real use case does that enable?
Short answer
Implement __delete__(self, instance) to run custom logic when 'del instance.attr' is called — useful for cleanup actions (like closing a resource, invalidating a related cache, or resetting to a default) that should happen specifically when an attribute is explicitly removed…
Advertisement
AModel answer
Implement __delete__(self, instance) to run custom logic when 'del instance.attr' is called — useful for cleanup actions (like closing a resource, invalidating a related cache, or resetting to a default) that should happen specifically when an attribute is explicitly removed rather than just reassigned.
class ManagedResource:
def __set_name__(self, owner, name):
self.name = f"_{name}"
def __get__(self, instance, owner):
return getattr(instance, self.name, None)
def __set__(self, instance, value):
setattr(instance, self.name, value)
def __delete__(self, instance):
resource = getattr(instance, self.name, None)
if resource:
resource.close() # cleanup runs specifically on 'del'
delattr(instance, self.name)Real-world example
Ensuring a resource (like a file handle stored on an object) is properly released when its attribute is explicitly deleted with 'del'.
Likely follow-ups
- How does this differ in behavior and trigger conditions from cleanup logic placed in a class's __del__ method instead?
Related topics