Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better in python, del or delattr?

Tags:

python

del

People also ask

Should I use del in Python?

The del keyword is used to delete objects. In Python everything is an object, so the del keyword can also be used to delete variables, lists, or parts of a list etc.

What is __ Delattr __ in Python?

The delattr() method is used to delete the named attribute from the object, with the prior permission of the object. Syntax: delattr(object, name) The function takes only two parameter: object : from which the name attribute is to be removed.

Why is Del not a function Python?

Because del is a statement that you can delete several things with it, and since when you want to delete list_name[index] with del actually you want to delete an object and this is the job that del does for other objects so there is no need to create an redundant attribute for lists to does that!

What does Del return in Python?

Return Value of Python del Python del statement doesn't return anything.


The first is more efficient than the second. del foo.bar compiles to two bytecode instructions:

  2           0 LOAD_FAST                0 (foo)
              3 DELETE_ATTR              0 (bar)

whereas delattr(foo, "bar") takes five:

  2           0 LOAD_GLOBAL              0 (delattr)
              3 LOAD_FAST                0 (foo)
              6 LOAD_CONST               1 ('bar')
              9 CALL_FUNCTION            2
             12 POP_TOP             

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 and LOAD_GLOBAL]


  • del is more explicit and efficient;
  • delattr allows dynamic attribute deleting.

Consider the following examples:

for name in ATTRIBUTES:
    delattr(obj, name)

or:

def _cleanup(self, name):
    """Do cleanup for an attribute"""
    value = getattr(self, name)
    self._pre_cleanup(name, value)
    delattr(self, name)
    self._post_cleanup(name, value)

You can't do it with del.


Unquestionably the former. In my view this is like asking whether foo.bar is better than getattr(foo, "bar"), and I don't think anyone is asking that question :)


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.