Delattr option to ignore AttributeError

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:

try:
    delattr(object, attr)
except AttributeError:
    pass

or

if hasattr(object, attr):
    delattr(object, attr)

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')

Would anyone else find this useful?

In all my years of using python, I’ve never seen this pattern. So my sample size of one says “no, it’s not common”.

Why not just write your own helper function that does this? As you’ve shown, it’s only a couple of lines of code.

I’m curious: what coding pattern are you using that causes you to delete object attributes often?

1 Like

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.

1 Like

How few? I have found only two occurrences, both in the IDLE code.

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.