[Python-ideas] clear() method for lists
george.sakkis at gmail.com
Fri Apr 3 20:00:07 CEST 2009
On Fri, Apr 3, 2009 at 1:33 PM, Gerald Britton <gerald.britton at gmail.com> wrote:
> About your example, what is the advantage over inheriting from list?
The fact that you can pick and choose which methods to provide, while
with inheritance you get all of them whether you want them or not. For
example one may want to create a FixedSizeList that provides only the
read-only methods plus __setitem__, but not any method that changes
the size of the list. Although you could emulate that with inheritance
(by making all forbidden methods raise AttributeError), it's less
clear than delegation and it breaks introspection.
> 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[:]
>>> 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.
>> 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
>> 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
> Gerald Britton
> Python-ideas mailing list
> Python-ideas at python.org
More information about the Python-ideas