Recently I’ve been working on a code base that regularly does the pattern of deleting an attribute of an object, but only if that attribute exists. This can either be done with:
I imagine this is a fairly common pattern. My suggestion would be an option in delattr to ignore if the attr doesn’t exist, something like delattr(object, attr, missing='ignore')
Well I think to start with delattr is probably not used too much, but looking through times when it is used in open source projects it seems like around 1/3 of the time it is used in the above pattern (from some very rough searching).
I could write a helper function to do this, although I guess the same could be said for hasattr which is only a try/except around getattr, and even for the default option in getattr which could be just a try/except around getattr without the default. When I saw all of the try/excepts around the delattrs in the codebase, I looked to the python docs expecting an option to exist for this.
The main time this comes up is when you need to delete an attr, but you don’t know enough about the object you are deleting it from to know whether it exists yet or not (maybe the attr only gets created by some method which may not have been called yet). This pattern does come up a few times in the stdlib.
Not at my computer right now but I seem to remember finding it in configparser and unittest as well, although yes I am talking about only 4 or 5 times (but then delattr only appears a handful of times in stdlib anyway)
The code in configparser and unittest is different, because it performs other actions depending on the existence of the specified attribute, not only removes it. delattr() ignoring AttributeError would not be useful here.
So, we have exactly two cases of this pattern in more than 100 thousand lines of code. In my opinion, this is not enough.