Search code examples
pythonpython-datamodel

Example of a custom deleter method


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)

Solution

  • 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