Customizing __delattr__ in python

Viewed 313

Is the following a valid __delattr__ method?

class Item:
    def __delattr__(self, attr):
        if attr in self.__dict__:
            print ('Deleting attribute: %s' % attr)
            super().__delattr__(attr)
        else:
            print ('Already deleted this attribute!')

Specifically, is the super() the proper way to "actually delete" the attributes? And is the attr in self.__dict__ the proper way to check if an attribute is in an instance?

1 Answers

Super would call the corresponding method of the parent class, you can implement your own special method here and don't need to refer to its super implementation. Consider the following:

class Item:
    def __delattr__(self, attr):
        try:
            print ('Deleting attribute: %s' % attr)
            del self.__dict__[attr]
        except KeyError:
            print ('Already deleted this attribute!')

Testing the class:

>>> i.test = 'a value'
>>> del i.test
Deleting attribute: test
>>> del i.test
Deleting attribute: test
Already deleted this attribute!
Related