Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5cab2e3

Browse files
committed
Give itertools.repeat() a length method.
1 parent 27da291 commit 5cab2e3

2 files changed

Lines changed: 21 additions & 2 deletions

File tree

Lib/test/test_itertools.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -607,6 +607,12 @@ def test_tee(self):
607607
self.assertRaises(TypeError, list, tee(N(s))[0])
608608
self.assertRaises(ZeroDivisionError, list, tee(E(s))[0])
609609

610+
class LengthTransparency(unittest.TestCase):
611+
612+
def test_repeat(self):
613+
self.assertEqual(len(repeat(None, 50)), 50)
614+
self.assertRaises(TypeError, len, repeat(None))
615+
610616
class RegressionTests(unittest.TestCase):
611617

612618
def test_sf_793826(self):
@@ -826,7 +832,7 @@ def f(t):
826832

827833
def test_main(verbose=None):
828834
test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC,
829-
RegressionTests)
835+
RegressionTests, LengthTransparency)
830836
test_support.run_unittest(*test_classes)
831837

832838
# verify reference counting

Modules/itertoolsmodule.c

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2347,6 +2347,19 @@ repeat_next(repeatobject *ro)
23472347
return ro->element;
23482348
}
23492349

2350+
static int
2351+
repeat_len(repeatobject *ro)
2352+
{
2353+
if (ro->cnt == -1)
2354+
PyErr_SetString(PyExc_TypeError, "len() of unsized object");
2355+
return (int)(ro->cnt);
2356+
}
2357+
2358+
static PySequenceMethods repeat_as_sequence = {
2359+
(inquiry)repeat_len, /* sq_length */
2360+
0, /* sq_concat */
2361+
};
2362+
23502363
PyDoc_STRVAR(repeat_doc,
23512364
"repeat(element [,times]) -> create an iterator which returns the element\n\
23522365
for the specified number of times. If not specified, returns the element\n\
@@ -2366,7 +2379,7 @@ static PyTypeObject repeat_type = {
23662379
0, /* tp_compare */
23672380
0, /* tp_repr */
23682381
0, /* tp_as_number */
2369-
0, /* tp_as_sequence */
2382+
&repeat_as_sequence, /* tp_as_sequence */
23702383
0, /* tp_as_mapping */
23712384
0, /* tp_hash */
23722385
0, /* tp_call */

0 commit comments

Comments
 (0)