[Python-ideas] clear() method for lists

Christian Heimes lists at cheimes.de
Sat Apr 4 02:56:47 CEST 2009


Andre Roberge wrote:
> Seeing mostly positive responses so far ... Is it worth writing a pre-PEP to
> formalize this suggestion?

The feature doesn't require a formal PEP. The implementation requires 10
lines of simple C code. For a full patch you have to provide a simple
_abscoll.MutableSequence.clear() method (just pop() until an IndexError
is raised), some documentation updates and a bunch of unit tests.

Christian

Index: Objects/listobject.c
===================================================================
--- Objects/listobject.c        (revision 71106)
+++ Objects/listobject.c        (working copy)
@@ -785,6 +785,14 @@
 }

 static PyObject *
+listclear(PyListObject *self, PyObject *unused)
+{
+       if (list_resize(self, 0) == 0)
+               Py_RETURN_NONE;
+       return NULL;
+}
+
+static PyObject *
 listextend(PyListObject *self, PyObject *b)
 {
        PyObject *it;      /* iter(v) */
@@ -2458,6 +2466,8 @@
 "L.__sizeof__() -- size of L in memory, in bytes");
 PyDoc_STRVAR(append_doc,
 "L.append(object) -- append object to end");
+PyDoc_STRVAR(clear_doc,
+"L.clear() -- clear the list");
 PyDoc_STRVAR(extend_doc,
 "L.extend(iterable) -- extend list by appending elements from the
iterable");
 PyDoc_STRVAR(insert_doc,
@@ -2486,6 +2496,7 @@
        {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS,
reversed_doc},
        {"__sizeof__",  (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
        {"append",      (PyCFunction)listappend,  METH_O, append_doc},
+       {"clear",       (PyCFunction)listclear,   METH_NOARGS, clear_doc},
        {"insert",      (PyCFunction)listinsert,  METH_VARARGS, insert_doc},
        {"extend",      (PyCFunction)listextend,  METH_O, extend_doc},
        {"pop",         (PyCFunction)listpop,     METH_VARARGS, pop_doc},


>>> l = [1, 2, 3]
[35104 refs]
>>> l
[1, 2, 3]
[35111 refs]
>>> l.clear()
[35111 refs]
>>> l
[]




More information about the Python-ideas mailing list