1

I have come across various examples of a custom getter or setter, but what would be a use case of when a custom deleter would be used? So far an example that I have is just something like this:

def __delattr__(self, attr):
    print('Deleting attr %s' % attr)
    super().__delattr__(attr)
wim
  • 338,267
  • 99
  • 616
  • 750
David542
  • 104,438
  • 178
  • 489
  • 842
  • Can't speak to this definitively, hence why I am not putting in an answer, but perhaps your object has attributes which are set to other objects, and you might need to do some cleanup on those objects for deleting the reference to the variable. (E.g., peacefully terminating some kind of I/O stream or connection before deleting the reference to it.) I am simply speculating, though, as I have never seen a class override the `__delattr__(...)` method. – Spencer D Oct 15 '19 at 00:26

1 Answers1

1

It's a standard datamodel hook for customizing what a statement del obj.attr will do, instead of (or in addition to) removing the attribute from the instance __dict__. So, user code is free to implement whatever they want!

As an example, you could use it as a "soft delete" feature, e.g. to hide an attribute from public access without actually removing the data behind it. Personally, I have used it to invalidate caches when the corresponding get attribute method has a caching layer in front of it.

For a stdlib example, consider the Mock class. By default, mock instances will generate child mocks for any attribute access. The public API to "opt-out" of a child mock being auto-generated on a particular name is implemented via a custom __delattr__.

>>> from unittest.mock import Mock  
>>> mock = Mock()   
>>> del mock.attr2  # prevent mock.attr2 from working
>>> mock.attr1  
<Mock name='mock.attr1' id='4414043216'>
>>> mock.attr2
AttributeError: attr2
wim
  • 338,267
  • 99
  • 616
  • 750