Call "del" in the list

class ToBeDeleted:
    def __init__(self, value):
        self.value = val

    # Whatever...

    def __del__(self):
        print self.value

l = [ToBeDeleted(i) for i in range(3)]
del l

Will print 2, 1, 0.


  • Now, is the order of the deleted elements defined somewhere in the specification, or is it implementation specific? (or maybe I don't understand the basic mechanics)

  • Could there be a way out, for example 0, 1, 2? I understand that the order 2, 1, 0is probably made to avoid reallocating memory for items when they are deleted, but the question remains.

  • And the last - what is the difference between operators del land del l[:]?

+5
source share
3 answers

del l , l . , del l[:] , l .

__del__ - , , .

. del l, , , , l .

pypy , . , GC .

cpython OP , . del l[:] , : http://hg.python.org/cpython/file/2.7/Objects/listobject.c#l700. del l, : http://hg.python.org/cpython/file/2.7/Objects/listobject.c#l596

+8

. , CPython.

list_dealloc listobject.c , :

    /* Do it backwards, for Christian Tismer.
       There a simple test case where somehow this reduces
       thrashing when a *very* large list is created and
       immediately deleted. */
+2
  • .
  • , , - ( , , ) . , . , , ; .
  • del l (, , , ), del l[:] . del l; print l.
+1

All Articles