This may be silly, but it's been nagging the back of my brain for a while.
Python gives us two built-in ways to delete attributes from objects, the del command word and the delattr built-in function. I prefer delattr because it I think its a bit more explicit:
del foo.bar
delattr(foo, "bar")
But I'm wondering if there might be under-the-hood differences between them.
It is an old question, but I would like to put my 2 cents in.
Though,
del foo.bar
is more elegant, at times you will needdelattr(foo, "bar")
. Say, if you have an interactive command line interface that allows a user to dynamically delete any member in the object by typing the name, then you have no choice but to use the latter form.It's really a matter of preference, but the first is probably preferable. I'd only use the second one if you don't know the name of the attribute that you're deleting ahead of time.