[Python-ideas] clear() method for lists

Mark Summerfield list at qtrac.plus.com
Sun Apr 5 09:29:24 CEST 2009


On 2009-04-03, Gerald Britton wrote:
> About your example, what is the advantage over inheriting from list?
> I did this myself to build a kind of treed list class that supports
> nested lists:
>
> Class TreeList(list):
>  # uses most list methods
>    def __iter__:
>    # does a recursive descent through nested lists.
>
> I only had to implement methods that I wanted to add some extra sauce to.

Yes, but sometimes you need something that offers _less_ functionality
than a list (e.g., you could create a stack or queue by aggregating a
list), in which case it is easier to aggregate and just add or delegate
the methods you want without having to worry about "unimplementing"
those that you don't want---although unimplementing is possible of
course.

>
> On Fri, Apr 3, 2009 at 7:15 AM, Mark Summerfield <list at qtrac.plus.com> 
wrote:
> > 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
> >
> > _______________________________________________
> > Python-ideas mailing list
> > Python-ideas at python.org
> > http://mail.python.org/mailman/listinfo/python-ideas


-- 
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
    C++, Python, Qt, PyQt - training and consultancy
        "C++ GUI Programming with Qt 4" - ISBN 0132354160




More information about the Python-ideas mailing list