From 435bf58b7bc9df7dd8683c3fc72b5b7ca1316541 Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Thu, 18 Mar 2004 22:43:10 +0000 Subject: [PATCH] Make iterators length transparent where possible. --- Objects/iterobject.c | 15 ++++++++++++++- Objects/listobject.c | 15 ++++++++++++++- Objects/tupleobject.c | 15 ++++++++++++++- 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/Objects/iterobject.c b/Objects/iterobject.c index abcf8db1fe3..a407dd597fd 100644 --- a/Objects/iterobject.c +++ b/Objects/iterobject.c @@ -71,6 +71,19 @@ iter_iternext(PyObject *iterator) return NULL; } +static int +iter_len(seqiterobject *it) +{ + if (it->it_seq) + return PyObject_Size(it->it_seq) - it->it_index; + return 0; +} + +static PySequenceMethods iter_as_sequence = { + (inquiry)iter_len, /* sq_length */ + 0, /* sq_concat */ +}; + PyTypeObject PySeqIter_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, /* ob_size */ @@ -85,7 +98,7 @@ PyTypeObject PySeqIter_Type = { 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ - 0, /* tp_as_sequence */ + &iter_as_sequence, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ diff --git a/Objects/listobject.c b/Objects/listobject.c index 3bda2453038..f34ca70abcb 100644 --- a/Objects/listobject.c +++ b/Objects/listobject.c @@ -2707,6 +2707,19 @@ listiter_next(listiterobject *it) return NULL; } +static int +listiter_len(listiterobject *it) +{ + if (it->it_seq) + return PyList_GET_SIZE(it->it_seq) - it->it_index; + return 0; +} + +static PySequenceMethods listiter_as_sequence = { + (inquiry)listiter_len, /* sq_length */ + 0, /* sq_concat */ +}; + PyTypeObject PyListIter_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, /* ob_size */ @@ -2721,7 +2734,7 @@ PyTypeObject PyListIter_Type = { 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ - 0, /* tp_as_sequence */ + &listiter_as_sequence, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ diff --git a/Objects/tupleobject.c b/Objects/tupleobject.c index 66fb146174c..60878a43145 100644 --- a/Objects/tupleobject.c +++ b/Objects/tupleobject.c @@ -839,6 +839,19 @@ tupleiter_next(tupleiterobject *it) return NULL; } +static int +tupleiter_len(tupleiterobject *it) +{ + if (it->it_seq) + return PyTuple_GET_SIZE(it->it_seq) - it->it_index; + return 0; +} + +static PySequenceMethods tupleiter_as_sequence = { + (inquiry)tupleiter_len, /* sq_length */ + 0, /* sq_concat */ +}; + PyTypeObject PyTupleIter_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, /* ob_size */ @@ -853,7 +866,7 @@ PyTypeObject PyTupleIter_Type = { 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ - 0, /* tp_as_sequence */ + &tupleiter_as_sequence, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */