From 85c20a41dfcec04d161ad7da7260e7b94c62d228 Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Thu, 6 Nov 2003 14:06:48 +0000 Subject: Implement and apply PEP 322, reverse iteration --- Objects/rangeobject.c | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) (limited to 'Objects/rangeobject.c') diff --git a/Objects/rangeobject.c b/Objects/rangeobject.c index 299f4a651f9..1f5672804f3 100644 --- a/Objects/rangeobject.c +++ b/Objects/rangeobject.c @@ -171,6 +171,15 @@ static PySequenceMethods range_as_sequence = { }; static PyObject * range_iter(PyObject *seq); +static PyObject * range_reverse(PyObject *seq); + +PyDoc_STRVAR(reverse_doc, +"Returns a reverse iterator."); + +static PyMethodDef range_methods[] = { + {"__reversed__", (PyCFunction)range_reverse, METH_NOARGS, reverse_doc}, + {NULL, NULL} /* sentinel */ +}; PyTypeObject PyRange_Type = { PyObject_HEAD_INIT(&PyType_Type) @@ -201,7 +210,7 @@ PyTypeObject PyRange_Type = { 0, /* tp_weaklistoffset */ (getiterfunc)range_iter, /* tp_iter */ 0, /* tp_iternext */ - 0, /* tp_methods */ + range_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ @@ -245,6 +254,32 @@ range_iter(PyObject *seq) return (PyObject *)it; } +static PyObject * +range_reverse(PyObject *seq) +{ + rangeiterobject *it; + long start, step, len; + + if (!PyRange_Check(seq)) { + PyErr_BadInternalCall(); + return NULL; + } + it = PyObject_New(rangeiterobject, &Pyrangeiter_Type); + if (it == NULL) + return NULL; + + start = ((rangeobject *)seq)->start; + step = ((rangeobject *)seq)->step; + len = ((rangeobject *)seq)->len; + + it->index = 0; + it->start = start + (len-1) * step; + it->step = -step; + it->len = len; + + return (PyObject *)it; +} + static PyObject * rangeiter_next(rangeiterobject *r) { -- cgit v1.2.3