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.
Not sure about the inner workings, but from a code reusability and don't be a jerk coworker perspective, use del. It's more clear and understood by people coming from other languages as well.
If you think
delattr
is more explicit, then why not usedgetattr
all the time rather thanobject.attr
?As for under the hood... your guess is as good as mine. If not significantly better.
Consider the following examples:
or:
You can't do it with del.
The first is more efficient than the second.
del foo.bar
compiles to two bytecode instructions:whereas
delattr(foo, "bar")
takes five:This translates into the first running slightly faster (but it's not a huge difference – .15 μs on my machine).
Like the others have said, you should really only use the second form when the attribute that you're deleting is determined dynamically.
[Edited to show the bytecode instructions generated inside a function, where the compiler can use
LOAD_FAST
andLOAD_GLOBAL
]Just like getattr and setattr, delattr should only be used when the attribute name is unknown.
In that sense, it's roughly equivalent to several python features that are used to access built-in functionality at a lower level than you normally have available, such as
__import__
instead ofimport
andoperator.add
instead of+
Unquestionably the former. In my view this is like asking whether
foo.bar
is better thangetattr(foo, "bar")
, and I don't think anyone is asking that question :)