[Python-Dev] PEP 203 Augmented Assignment
Michael Hudson
mwh21@cam.ac.uk
27 Jul 2000 21:41:02 +0100
Guido van Rossum <guido@beopen.com> writes:
> > Good idea. Are lists and tuples going to support seq[a:b:c] anytime soon?
>
> It's on my wish list, but can't be done for 2.0.
This would involve the list type implementing the mapping API wouldn't
it? This would seem to be a little on the silly side. Never mind;
here's a quick-hack patch that "seems to work" for lists:
Index: listobject.c
===================================================================
RCS file: /cvsroot/python/python/dist/src/Objects/listobject.c,v
retrieving revision 2.83
diff -u -c -r2.83 listobject.c
*** listobject.c 2000/07/25 12:56:38 2.83
--- listobject.c 2000/07/27 20:38:50
***************
*** 1400,1405 ****
--- 1400,1441 ----
(objobjproc)list_contains, /*sq_contains*/
};
+ static PyObject*
+ list_subscript(PyObject* list, PyObject* item)
+ {
+ if (PyInt_Check(item)) {
+ return list_item((PyListObject*)list,PyInt_AS_LONG(item));
+ } else if (PySlice_Check(item)) {
+ int start, stop, step, cur, i;
+ PyObject* result;
+ PyObject* it;
+
+ if (PySlice_GetIndices((PySliceObject*)item,PyList_Size(list),&start,&stop,&step) < 0) {
+ PyErr_SetString(PyExc_TypeError, "slice indices must be integers");
+ return NULL;
+ }
+
+ result = PyList_New((stop-start)/step+1);
+
+ for (cur = start, i = 0; cur < stop; cur += step, i++) {
+ it = PyList_GET_ITEM(list,cur);
+ Py_INCREF(it);
+ PyList_SET_ITEM(result,i,it);
+ }
+
+ return result;
+ } else {
+ PyErr_SetString(PyExc_TypeError, "list indices must be integers");
+ return NULL;
+ }
+ };
+
+ static PyMappingMethods list_as_mapping = {
+ (inquiry)list_length,
+ (binaryfunc)list_subscript,
+ (objobjargproc)NULL
+ };
+
PyTypeObject PyList_Type = {
PyObject_HEAD_INIT(&PyType_Type)
0,
***************
*** 1414,1420 ****
(reprfunc)list_repr, /*tp_repr*/
0, /*tp_as_number*/
&list_as_sequence, /*tp_as_sequence*/
! 0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
--- 1450,1456 ----
(reprfunc)list_repr, /*tp_repr*/
0, /*tp_as_number*/
&list_as_sequence, /*tp_as_sequence*/
! &list_as_mapping, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
Have I missed anything obvious? I'd upload it to SF, but I don't
really want something I've put such little effort into to be seriously
considered...
Cheers,
M.
--
112. Computer Science is embarrassed by the computer.
-- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html