[Python-ideas] clear() method for lists

Mark Summerfield list at qtrac.plus.com
Fri Apr 3 13:15:20 CEST 2009


On 2009-04-03, Andre Roberge wrote:
> Hi everyone,
>
> On the general Python list, a suggestion was made to add a clear() method
> to list, as the "obvious" way to do
> del some_list[:]
> or
> some_list[:] = []
>
> since the clear() method is currently the obvious way to remove all
> elements from dict and set objects.
>
> I believe that this would be a lot more intuitive to beginners learning the
> language, making Python more uniform.
>
> André

Hi,

I have a use case for list.clear() (might be a bit obscure though).

If you have a class that includes a list as an attribute (e.g., a list
"subclass" that uses aggregation rather than inheritance), you might
want to delegate many list methods to the list attribute and only
implement those you want to treat specially. I show an example of this
in "Programming in Python 3" (pages 367/8) where I have a @delegate
decorator that accepts an attribute name and a tuple of methods to
delegate to, e.g.:

    @delegate("__list", ("pop", "__delitem__", "__getitem_", ...))
    class MyList:
	...
	def clear(self):
	    self.__list = []

But because there is no list.clear(), the clear() method must be
implemented rather than delegated even though it doesn't do anything
special.


+1

-- 
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
    C++, Python, Qt, PyQt - training and consultancy
	"Programming in Python 3" - ISBN 0137129297




More information about the Python-ideas mailing list