[Python-ideas] clear() method for lists

Gerald Britton gerald.britton at gmail.com
Fri Apr 3 19:33:14 CEST 2009


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.


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
>



-- 
Gerald Britton



More information about the Python-ideas mailing list