Skip to content

Commit c821183

Browse files
committed
mirror c code more closely with itertools.repeat
1 parent 5ac0e11 commit c821183

File tree

1 file changed

+29
-16
lines changed

1 file changed

+29
-16
lines changed

graalpython/lib-graalpython/itertools.py

Lines changed: 29 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -25,41 +25,54 @@
2525

2626

2727
class repeat():
28+
"""
29+
repeat(object [,times]) -> create an iterator which returns the object\n\
30+
for the specified number of times. If not specified, returns the object\n\
31+
endlessly.
32+
"""
2833
@__graalpython__.builtin_method
29-
def __init__(self, obj, times=None):
30-
self.obj = obj
31-
self.times = times
34+
def __init__(self, object, times=None):
35+
self.element = object
3236
if times is not None and not isinstance(times, int):
3337
raise TypeError(f"integer argument expected, got {times.__class__.__name__}")
34-
self.count = times if times and times > 0 else 0
38+
if times is not None:
39+
if times < 0:
40+
self.cnt = 0
41+
else:
42+
self.cnt = times
43+
else:
44+
self.cnt = -1
3545

3646
@__graalpython__.builtin_method
3747
def __iter__(self):
3848
return self
3949

4050
@__graalpython__.builtin_method
4151
def __next__(self):
42-
if self.times is not None:
43-
if self.count == 0:
44-
raise StopIteration
45-
self.count -= 1
46-
return self.obj
52+
if self.cnt == 0:
53+
raise StopIteration
54+
elif self.cnt > 0:
55+
self.cnt -= 1
56+
return self.element
4757

4858
@__graalpython__.builtin_method
4959
def __length_hint__(self):
50-
return self.count
60+
if self.cnt == -1:
61+
raise TypeError("len() of unsized object")
62+
return self.cnt
5163

5264
@__graalpython__.builtin_method
5365
def __reduce__(self):
54-
if self.times is not None:
55-
return (self, (self.obj, self.count))
56-
return (self, (self.obj,))
66+
if self.cnt >= 0:
67+
return self, (self.element, self.cnt)
68+
return self, (self.element,)
5769

5870
@__graalpython__.builtin_method
5971
def __repr__(self):
60-
if self.times is not None:
61-
return "{}({}, {})".format(type(self).__name__, self.obj, self.count)
62-
return "{}({})".format(type(self).__name__, self.obj)
72+
if self.cnt == -1:
73+
return "{}({})".format(type(self).__name__, self.element)
74+
else:
75+
return "{}({}, {})".format(type(self).__name__, self.element, self.cnt)
6376

6477

6578
class chain():

0 commit comments

Comments
 (0)