How to clear a list (3 ways).

francois.petitjean at bureauveritas.com francois.petitjean at bureauveritas.com
Thu Mar 6 12:28:17 EST 2008


Consider the following code :
#!/usr/bin/env python
# -*- coding: latin_1 -*-

"""
container.py  how to clear a container
"""

class Container(object):
    def __init__(self):
        self.elts = {}
        self.parts = []
    def clear(self):
        self.elts.clear()  #  for a dictionary it's clear :-)
        self.parts = []       #  (1)
     #  self.parts[:] = []    #  (2)
     #  del self.parts[:]     #  (3)
    def __len__(self):
        return len(self.parts)
    def add_predicate(self, part):
        """return True if part should be added (to override)"""
        return True
    def add(self, part):
        """return True if part is added"""
        res = self.add_predicate(part)
        if res:
            self.parts.append(part)
            self.elts[str(part)] = part # or wahtever
        return res
    def replace_parts(self, values):
        """return True if all values are added/replaced"""
        acceptable = all(map(self.add_predicate, values))  # FIXME
itertools.imap ?
        if not acceptable:
            return acceptable
        self.parts[:] = values
        # TODO elts
        return acceptable

Container1 = Container

class Container2(Container):
    def clear(self):
        self.elts.clear()  #  for a dictionary it's clear :-)
        self.parts[:] = []    #  (2)

class Container3(Container):
    def clear(self):
        self.elts.clear()  #  for a dictionary it's clear :-)
        del self.parts[:]     #  (3)


Solution (1) is somewhat broken  (see the test_container.rst hereafter) but
often used. For instance in configobj we have
    def clear(self):
        """
        A version of clear that also affects scalars/sections
        Also clears comments and configspec.

        Leaves other attributes alone :
            depth/main/parent are not affected
        """
        dict.clear(self)
        self.scalars = []
        self.sections = []
        self.comments = {}
        self.inline_comments = {}
        self.configspec = {}

What idiom do you use (and prefer) ?


test_container.rst  can be used like this :
>>> import doctest
>>> doctest.testfile('test_container.rst', encoding='latin_1')
(nfails, ntests) is printed.
===================
test_container.rst
===================

>>> from container import Container1, Container2, Container3
>>> cont1 = Container1()
>>> cont1.add(1)
True
>>> cont1.add(2)
True
>>> cont1.add(3)
True
>>> parts = cont1.parts
>>> parts
[1, 2, 3]

The client has cached the parts attribute.
Solution (1) is not robust, is the parts attribute in the public API ?
>>> cont1.clear()
>>> parts
[1, 2, 3]
>>> cont1.parts, parts
([], [1, 2, 3])

We now have two different objects.

>>> cont2 = Container2()
>>> cont2.add(21)
True

>>> cont2.add(22)
True
>>> cont2.add(23)
True
>>> parts2 = cont2.parts
>>> parts2
[21, 22, 23]
>>> cont2.clear()
>>> parts2
[]
>>> cont1.parts, parts
([], [1, 2, 3])

>>> cont3 = Container3()
>>> cont3.add(31)
True
>>> cont3.add(32)
True
>>> parts3 = cont3.parts
>>> cont3.add(33)
True
>>> parts3
[31, 32, 33]
>>> cont3.clear()
>>> parts3
[]

Test de replace_parts

>>> cont3 = Container3()
>>> len(cont3)
0
>>> parts3 = cont3.parts
>>> cont3.add(30)
True
>>> parts3
[30]
>>> cont3.replace_parts( (31, 32, 33) )
True
>>> parts3
[31, 32, 33]
>>>


Regards.
   NOTICE: This message contains information which is confidential and the
   copyright of our company or a third  party. If you are not the intended
   recipient of this message please delete it and destroy all copies. If
   you
   are the intended recipient of this message you should not disclose or
   distribute this message to third parties without the consent of our
   company. Our company does not represent, warrant and/or guarantee that
   the integrity of this message has been maintained nor that the
   communication is free of virus, interception or interference. The
   liability of our company is limited by our General Conditions of
   Services.
   Nota : Ce message contient des informations confidentielles propriété de
   notre société et/ou d'un tiers. Si vous n’êtes pas parmi les
   destinataires désignés de ce message, merci de l'effacer ainsi que
   toutes ses copies. Si vous êtes parmi les destinataires désignés de ce
   message, prière de ne pas le divulguer ni de le transmettre à des tiers
   sans l’accord de notre société. Notre société ne peut garantir que
   l’intégrité de ce message a été préservée ni que la présente
   communication est sans virus, interception ou interférence. La
   responsabilité de notre société est limitée par nos Conditions Générales
   de Services.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080306/fa4c69c1/attachment.html>


More information about the Python-list mailing list