Debian Codegraph @

pypy/module/itertools/interp_itertools.py

raw symbols SCIP
1 from pypy.interpreter.baseobjspace import W_Root
2 from pypy.interpreter.error import OperationError, oefmt
3 from pypy.interpreter.typedef import TypeDef, make_weakref_descr
4 from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault
5 from pypy.objspace.std.util import generic_alias_class_getitem, builtinclass_new_args_check
6 from rpython.rlib import jit
7 from rpython.rtyper.lltypesystem import rffi
8
9 from pypy.module.__builtin__.functional import W_Filter, build_iterators_from_args
10
11 def W_Twoarg__new__(space, w_subtype, W_Base, name, __args__):
12 args_w = __args__.arguments_w
13 w_type = space.gettypeobject(W_Base.typedef)
14 w_init = space.newtext("__init__")
15 if (space.is_w(w_subtype, w_type) or
16 space.is_w(space.getattr(w_subtype, w_init), space.getattr(w_type, w_init))):
17 if __args__.keyword_names_w:
18 raise oefmt(space.w_TypeError,
19 "%s() takes no keyword arguments", name)
20 length = len(args_w) if args_w else 0
21 if length != 2:
22 raise oefmt(space.w_TypeError,
23 "%s() expected 2 arguments, got %d", name, length)
24 return args_w
25
26
27 class W_Count(W_Root):
28 def __init__(self, space, w_firstval, w_step):
29 self.space = space
30 self.w_c = w_firstval
31 self.w_step = w_step
32
33 def iter_w(self):
34 return self
35
36 def next_w(self):
37 w_c = self.w_c
38 self.w_c = self.space.add(w_c, self.w_step)
39 return w_c
40
41 def single_argument(self):
42 space = self.space
43 return (space.isinstance_w(self.w_step, space.w_int) and
44 space.eq_w(self.w_step, space.newint(1)))
45
46 def repr_w(self):
47 space = self.space
48 cls_name = space.type(self).getname(space)
49 c = space.text_w(space.repr(self.w_c))
50 if self.single_argument():
51 s = '%s(%s)' % (cls_name, c)
52 else:
53 step = space.text_w(space.repr(self.w_step))
54 s = '%s(%s, %s)' % (cls_name, c, step)
55 return self.space.newtext(s)
56
57 def reduce_w(self):
58 space = self.space
59 if self.single_argument():
60 args_w = [self.w_c]
61 else:
62 args_w = [self.w_c, self.w_step]
63 return space.newtuple2(space.gettypefor(W_Count),
64 space.newtuple(args_w))
65
66 def check_number(space, w_obj):
67 if (space.lookup(w_obj, '__int__') is None and
68 space.lookup(w_obj, '__float__') is None and
69 not space.isinstance_w(w_obj, space.w_complex)
70 ):
71 raise oefmt(space.w_TypeError, "expected a number")
72
73 @unwrap_spec(w_start=WrappedDefault(0), w_step=WrappedDefault(1))
74 def W_Count___new__(space, w_subtype, w_start, w_step):
75 check_number(space, w_start)
76 check_number(space, w_step)
77 r = space.allocate_instance(W_Count, w_subtype)
78 r.__init__(space, w_start, w_step)
79 return r
80
81 W_Count.typedef = TypeDef(
82 'itertools.count',
83 __new__ = interp2app(W_Count___new__),
84 __iter__ = interp2app(W_Count.iter_w),
85 __next__ = interp2app(W_Count.next_w),
86 __reduce__ = interp2app(W_Count.reduce_w),
87 __repr__ = interp2app(W_Count.repr_w),
88 __doc__ = """Make an iterator that returns evenly spaced values starting
89 with n. If not specified n defaults to zero. Often used as an
90 argument to imap() to generate consecutive data points. Also,
91 used with izip() to add sequence numbers.
92
93 Equivalent to:
94
95 def count(start=0, step=1):
96 n = start
97 while True:
98 yield n
99 n += step
100 """)
101
102
103 class W_Repeat(W_Root):
104 def __init__(self, space, w_obj, w_times):
105 self.space = space
106 self.w_obj = w_obj
107
108 if w_times is None:
109 self.counting = False
110 self.count = 0
111 else:
112 self.counting = True
113 self.count = max(self.space.int_w(w_times), 0)
114
115 def next_w(self):
116 if self.counting:
117 if self.count <= 0:
118 raise OperationError(self.space.w_StopIteration, self.space.w_None)
119 self.count -= 1
120 return self.w_obj
121
122 def iter_w(self):
123 return self
124
125 def length_w(self):
126 if not self.counting:
127 return self.space.w_NotImplemented
128 return self.space.newint(self.count)
129
130 def repr_w(self):
131 space = self.space
132 cls_name = space.type(self).getname(space)
133 objrepr = self.space.text_w(space.repr(self.w_obj))
134 if self.counting:
135 s = '%s(%s, %d)' % (cls_name, objrepr, self.count)
136 else:
137 s = '%s(%s)' % (cls_name, objrepr)
138 return self.space.newtext(s)
139
140 def descr_reduce(self):
141 space = self.space
142 if self.counting:
143 args_w = [self.w_obj, space.newint(self.count)]
144 else:
145 args_w = [self.w_obj]
146 return space.newtuple([space.gettypefor(W_Repeat),
147 space.newtuple(args_w)])
148
149 def W_Repeat___new__(space, w_subtype, w_object, w_times=None):
150 r = space.allocate_instance(W_Repeat, w_subtype)
151 r.__init__(space, w_object, w_times)
152 return r
153
154 W_Repeat.typedef = TypeDef(
155 'itertools.repeat',
156 __new__ = interp2app(W_Repeat___new__),
157 __iter__ = interp2app(W_Repeat.iter_w),
158 __length_hint__ = interp2app(W_Repeat.length_w),
159 __next__ = interp2app(W_Repeat.next_w),
160 __repr__ = interp2app(W_Repeat.repr_w),
161 __reduce__ = interp2app(W_Repeat.descr_reduce),
162 __doc__ = """Make an iterator that returns object over and over again.
163 Runs indefinitely unless the times argument is specified. Used
164 as argument to imap() for invariant parameters to the called
165 function.
166
167 Equivalent to :
168
169 def repeat(object, times=None):
170 if times is None:
171 while True:
172 yield object
173 else:
174 for i in xrange(times):
175 yield object
176 """)
177
178
179 class W_TakeWhile(W_Root):
180 def __init__(self, space, w_predicate, w_iterable):
181 self.space = space
182 self.w_predicate = w_predicate
183 self.w_iterable = space.iter(w_iterable)
184 self.stopped = False
185
186 def iter_w(self):
187 return self
188
189 def next_w(self):
190 if self.stopped:
191 raise OperationError(self.space.w_StopIteration, self.space.w_None)
192
193 w_obj = self.space.next(self.w_iterable) # may raise a w_StopIteration
194 w_bool = self.space.call_function(self.w_predicate, w_obj)
195 if not self.space.is_true(w_bool):
196 self.stopped = True
197 raise OperationError(self.space.w_StopIteration, self.space.w_None)
198
199 return w_obj
200
201 def descr_reduce(self, space):
202 return space.newtuple([
203 space.type(self),
204 space.newtuple([self.w_predicate, self.w_iterable]),
205 space.newbool(self.stopped)
206 ])
207
208 def descr_setstate(self, space, w_state):
209 self.stopped = space.bool_w(w_state)
210
211 def W_TakeWhile___new__(space, w_subtype, __args__):
212 args_w = W_Twoarg__new__(space, w_subtype, W_TakeWhile, "takewhile", __args__)
213 r = space.allocate_instance(W_TakeWhile, w_subtype)
214 r.__init__(space, args_w[0], args_w[1])
215 return r
216
217 W_TakeWhile.typedef = TypeDef(
218 'itertools.takewhile',
219 __new__ = interp2app(W_TakeWhile___new__),
220 __iter__ = interp2app(W_TakeWhile.iter_w),
221 __next__ = interp2app(W_TakeWhile.next_w),
222 __reduce__ = interp2app(W_TakeWhile.descr_reduce),
223 __setstate__ = interp2app(W_TakeWhile.descr_setstate),
224 __doc__ = """Make an iterator that returns elements from the iterable as
225 long as the predicate is true.
226
227 Equivalent to :
228
229 def takewhile(predicate, iterable):
230 for x in iterable:
231 if predicate(x):
232 yield x
233 else:
234 break
235 """)
236
237
238 class W_DropWhile(W_Root):
239 def __init__(self, space, w_predicate, w_iterable):
240 self.space = space
241 self.w_predicate = w_predicate
242 self.w_iterable = space.iter(w_iterable)
243 self.started = False
244
245 def iter_w(self):
246 return self
247
248 def next_w(self):
249 if self.started:
250 w_obj = self.space.next(self.w_iterable) # may raise w_StopIter
251 else:
252 while True:
253 w_obj = self.space.next(self.w_iterable) # may raise w_StopIter
254 w_bool = self.space.call_function(self.w_predicate, w_obj)
255 if not self.space.is_true(w_bool):
256 self.started = True
257 break
258
259 return w_obj
260
261 def descr_reduce(self, space):
262 return space.newtuple([
263 space.type(self),
264 space.newtuple([self.w_predicate, self.w_iterable]),
265 space.newbool(self.started)
266 ])
267
268 def descr_setstate(self, space, w_state):
269 self.started = space.bool_w(w_state)
270
271 def W_DropWhile___new__(space, w_subtype, __args__):
272 args_w = W_Twoarg__new__(space, w_subtype, W_DropWhile, "dropwhile", __args__)
273 r = space.allocate_instance(W_DropWhile, w_subtype)
274 r.__init__(space, args_w[0], args_w[1])
275 return r
276
277
278 W_DropWhile.typedef = TypeDef(
279 'itertools.dropwhile',
280 __new__ = interp2app(W_DropWhile___new__),
281 __iter__ = interp2app(W_DropWhile.iter_w),
282 __next__ = interp2app(W_DropWhile.next_w),
283 __reduce__ = interp2app(W_DropWhile.descr_reduce),
284 __setstate__ = interp2app(W_DropWhile.descr_setstate),
285 __doc__ = """Make an iterator that drops elements from the iterable as long
286 as the predicate is true; afterwards, returns every
287 element. Note, the iterator does not produce any output until the
288 predicate is true, so it may have a lengthy start-up time.
289
290 Equivalent to :
291
292 def dropwhile(predicate, iterable):
293 iterable = iter(iterable)
294 for x in iterable:
295 if not predicate(x):
296 yield x
297 break
298 for x in iterable:
299 yield x
300 """)
301
302 class W_FilterFalse(W_Filter):
303 reverse = True
304 def descr_reduce(self, space):
305 args_w = [space.w_None if self.w_predicate is None else self.w_predicate,
306 self.w_iterable]
307 return space.newtuple([space.type(self), space.newtuple(args_w)])
308
309 def W_FilterFalse___new__(space, w_subtype, __args__):
310 args_w = W_Twoarg__new__(space, w_subtype, W_FilterFalse, 'filterfalse', __args__)
311 r = space.allocate_instance(W_FilterFalse, w_subtype)
312 r.__init__(space, args_w[0], args_w[1])
313 return r
314
315 W_FilterFalse.typedef = TypeDef(
316 'itertools.filterfalse',
317 __new__ = interp2app(W_FilterFalse___new__),
318 __iter__ = interp2app(W_FilterFalse.iter_w),
319 __next__ = interp2app(W_FilterFalse.next_w),
320 __reduce__ = interp2app(W_FilterFalse.descr_reduce),
321 __doc__ = """Make an iterator that filters elements from iterable returning
322 only those for which the predicate is False. If predicate is
323 None, return the items that are false.
324
325 Equivalent to :
326
327 def filterfalse(predicate, iterable):
328 if predicate is None:
329 predicate = bool
330 for x in iterable:
331 if not predicate(x):
332 yield x
333 """)
334
335
336 def get_printable_location(greenkey):
337 return "islice_ignore_items [%s]" % (greenkey.iterator_greenkey_printable(), )
338 islice_ignore_items_driver = jit.JitDriver(name='islice_ignore_items',
339 greens=['greenkey'],
340 reds=['w_islice', 'w_iterator'],
341 get_printable_location=get_printable_location)
342
343 class W_ISlice(W_Root):
344 def __init__(self, space, w_iterable, w_startstop, args_w):
345 self.iterable = space.iter(w_iterable)
346 self.space = space
347
348 num_args = len(args_w)
349
350 if num_args == 0:
351 start = 0
352 w_stop = w_startstop
353 elif num_args <= 2:
354 if space.is_w(w_startstop, space.w_None):
355 start = 0
356 else:
357 start = self.arg_int_w(w_startstop, 0,
358 "Indicies for islice() must be None or non-negative integers")
359 w_stop = args_w[0]
360 else:
361 raise oefmt(space.w_TypeError,
362 "islice() takes at most 4 arguments (%d given)",
363 num_args)
364
365 if space.is_w(w_stop, space.w_None):
366 stop = -1
367 else:
368 stop = self.arg_int_w(w_stop, 0,
369 "Stop argument must be a non-negative integer or None.")
370 stop = max(start, stop) # for obscure CPython compatibility
371
372 if num_args == 2:
373 w_step = args_w[1]
374 if space.is_w(w_step, space.w_None):
375 step = 1
376 else:
377 step = self.arg_int_w(w_step, 1,
378 "Step for islice() must be a positive integer or None")
379 else:
380 step = 1
381
382 self.count = rffi.cast(rffi.UNSIGNED, 0)
383 self.next = rffi.cast(rffi.UNSIGNED, start)
384 self.stop = stop
385 self.step = rffi.cast(rffi.UNSIGNED, step)
386
387 def arg_int_w(self, w_obj, minimum, errormsg):
388 space = self.space
389 try:
390 result = space.int_w(space.index(w_obj))
391 except OperationError as e:
392 if e.async(space):
393 raise
394 result = -1
395 if result < minimum:
396 raise OperationError(space.w_ValueError, space.newtext(errormsg))
397 return result
398
399 def iter_w(self):
400 return self
401
402 def next_w(self):
403 if self.iterable is None:
404 raise OperationError(self.space.w_StopIteration, self.space.w_None)
405 if self.count != self.next:
406 self._ignore_items()
407 stop = self.stop
408 if 0 <= stop <= self.count:
409 self.iterable = None
410 raise OperationError(self.space.w_StopIteration,
411 self.space.w_None)
412 try:
413 item = self.space.next(self.iterable)
414 except OperationError as e:
415 if e.match(self.space, self.space.w_StopIteration):
416 self.iterable = None
417 raise
418 self.count += 1
419 oldnext = self.next
420 new_next = self.next + self.step
421 if new_next < oldnext or (stop >=0 and new_next > rffi.cast(rffi.UNSIGNED,stop)):
422 self.next = rffi.cast(rffi.UNSIGNED, stop)
423 else:
424 self.next = new_next
425 return item
426
427 def _ignore_items(self):
428 w_iterator = self.iterable
429 greenkey = self.space.iterator_greenkey(w_iterator)
430 while True:
431 islice_ignore_items_driver.jit_merge_point(
432 greenkey=greenkey, w_islice=self, w_iterator=w_iterator)
433 if self.count >= self.next:
434 break
435 try:
436 self.space.next(w_iterator)
437 except OperationError as e:
438 if e.match(self.space, self.space.w_StopIteration):
439 self.iterable = None
440 raise
441 self.count += 1
442
443 def descr_reduce(self, space):
444 if self.iterable is None:
445 return space.newtuple([
446 space.type(self),
447 space.newtuple([space.iter(space.newlist([])),
448 space.newint(0)]),
449 space.newint(0),
450 ])
451 stop = self.stop
452 if stop == -1:
453 w_stop = space.w_None
454 else:
455 w_stop = space.newint(stop)
456 return space.newtuple([
457 space.type(self),
458 space.newtuple([self.iterable,
459 space.newint(self.next),
460 w_stop,
461 space.newint(self.step)]),
462 space.newint(self.count),
463 ])
464
465 def descr_setstate(self, space, w_state):
466 self.count = rffi.cast(rffi.UNSIGNED, space.int_w(w_state))
467
468 def W_ISlice___new__(space, w_subtype, w_iterable, w_startstop, __args__):
469 args_w = __args__.arguments_w
470 w_islice = space.gettypeobject(W_ISlice.typedef)
471 w_init = space.newtext("__init__")
472 if (space.is_w(w_subtype, w_islice) or
473 space.is_w(space.getattr(w_subtype, w_init), space.getattr(w_islice, w_init))):
474 if __args__.keyword_names_w:
475 raise oefmt(space.w_TypeError,
476 "islice() takes no keyword arguments")
477 r = space.allocate_instance(W_ISlice, w_subtype)
478 r.__init__(space, w_iterable, w_startstop, args_w)
479 return r
480
481 W_ISlice.typedef = TypeDef(
482 'itertools.islice',
483 __new__ = interp2app(W_ISlice___new__),
484 __iter__ = interp2app(W_ISlice.iter_w),
485 __next__ = interp2app(W_ISlice.next_w),
486 __reduce__ = interp2app(W_ISlice.descr_reduce),
487 __setstate__ = interp2app(W_ISlice.descr_setstate),
488 __doc__ = """Make an iterator that returns selected elements from the
489 iterable. If start is non-zero, then elements from the iterable
490 are skipped until start is reached. Afterward, elements are
491 returned consecutively unless step is set higher than one which
492 results in items being skipped. If stop is None, then iteration
493 continues until the iterator is exhausted, if at all; otherwise,
494 it stops at the specified position. Unlike regular slicing,
495 islice() does not support negative values for start, stop, or
496 step. Can be used to extract related fields from data where the
497 internal structure has been flattened (for example, a multi-line
498 report may list a name field on every third line).
499 """)
500
501
502 class W_Chain(W_Root):
503 def __init__(self, space, w_iterables):
504 self.space = space
505 self.w_iterables = w_iterables
506 self.w_it = None
507
508 def iter_w(self):
509 return self
510
511 def _advance(self):
512 if self.w_iterables is None:
513 raise OperationError(self.space.w_StopIteration, self.space.w_None)
514 self.w_it = self.space.iter(self.space.next(self.w_iterables))
515
516 def next_w(self):
517 if not self.w_it:
518 try:
519 self._advance()
520 except OperationError as e:
521 raise e
522 try:
523 return self.space.next(self.w_it)
524 except OperationError as e:
525 return self._handle_error(e)
526
527 def _handle_error(self, e):
528 while True:
529 if not e.match(self.space, self.space.w_StopIteration):
530 raise e
531 try:
532 self._advance() # may raise StopIteration itself
533 except OperationError as e:
534 self.w_iterables = None
535 raise e
536 try:
537 return self.space.next(self.w_it)
538 except OperationError as e:
539 pass # loop back to the start of _handle_error(e)
540
541 def descr_reduce(self, space):
542 if self.w_iterables is not None:
543 if self.w_it is not None:
544 inner_contents = [self.w_iterables, self.w_it]
545 else:
546 inner_contents = [self.w_iterables]
547 result_w = [space.type(self),
548 space.newtuple([]),
549 space.newtuple(inner_contents)]
550 else:
551 result_w = [space.type(self),
552 space.newtuple([])]
553 return space.newtuple(result_w)
554
555 def descr_setstate(self, space, w_state):
556 state = space.unpackiterable(w_state)
557 num_args = len(state)
558 if num_args < 1:
559 raise oefmt(space.w_TypeError,
560 "function takes at least 1 argument (%d given)",
561 num_args)
562 elif num_args == 1:
563 self.w_iterables = state[0]
564 elif num_args == 2:
565 self.w_iterables, self.w_it = state
566 else:
567 raise oefmt(space.w_TypeError,
568 "function takes at most 2 arguments (%d given)",
569 num_args)
570
571 def W_Chain___new__(space, w_subtype, __args__):
572 args_w = __args__.arguments_w
573 w_chain = space.gettypeobject(W_Chain.typedef)
574 w_init = space.newtext("__init__")
575 if (space.is_w(w_subtype, w_chain) or
576 space.is_w(space.getattr(w_subtype, w_init), space.getattr(w_chain, w_init))):
577 if __args__.keyword_names_w:
578 raise oefmt(space.w_TypeError,
579 "chain() takes no keyword arguments")
580 r = space.allocate_instance(W_Chain, w_subtype)
581 w_args = space.newtuple(args_w)
582 r.__init__(space, space.iter(w_args))
583 return r
584
585 def chain_from_iterable(space, w_cls, w_arg):
586 """chain.from_iterable(iterable) --> chain object
587
588 Alternate chain() constructor taking a single iterable argument
589 that evaluates lazily."""
590 r = space.allocate_instance(W_Chain, w_cls)
591 r.__init__(space, space.iter(w_arg))
592 return r
593
594 W_Chain.typedef = TypeDef(
595 'itertools.chain',
596 __new__ = interp2app(W_Chain___new__),
597 __iter__ = interp2app(W_Chain.iter_w),
598 __next__ = interp2app(W_Chain.next_w),
599 __reduce__ = interp2app(W_Chain.descr_reduce),
600 __setstate__ = interp2app(W_Chain.descr_setstate),
601 from_iterable = interp2app(chain_from_iterable, as_classmethod=True),
602 __class_getitem__ = interp2app(
603 generic_alias_class_getitem, as_classmethod=True),
604 __doc__ = """Make an iterator that returns elements from the first iterable
605 until it is exhausted, then proceeds to the next iterable, until
606 all of the iterables are exhausted. Used for treating consecutive
607 sequences as a single sequence.
608
609 Equivalent to :
610
611 def chain(*iterables):
612 for it in iterables:
613 for element in it:
614 yield element
615 """)
616
617
618 class W_ZipLongest(W_Root):
619 _immutable_fields_ = ["w_fillvalue", "iterators"]
620
621 def __init__(self, space, w_fun, args_w):
622 self.space = space
623 self.w_fun = w_fun
624 self.iterators_w = build_iterators_from_args(space, args_w)
625
626 def iter_w(self):
627 return self
628
629 def _fetch(self, index):
630 w_iter = self.iterators_w[index]
631 if w_iter is not None:
632 space = self.space
633 try:
634 return space.next(w_iter)
635 except OperationError as e:
636 if not e.match(space, space.w_StopIteration):
637 raise
638 self.active -= 1
639 if self.active <= 0:
640 # It was the last active iterator
641 raise
642 self.iterators_w[index] = None
643 return self.w_fillvalue
644
645 def next_w(self):
646 # common case: 2 arguments
647 if len(self.iterators_w) == 2:
648 return self.space.newtuple2(self._fetch(0), self._fetch(1))
649 else:
650 objects = self._get_objects()
651 return self.space.newtuple(objects)
652
653 def _get_objects(self):
654 # the loop is out of the way of the JIT
655 nb = len(self.iterators_w)
656 if nb == 0:
657 raise OperationError(self.space.w_StopIteration, self.space.w_None)
658 return [self._fetch(index) for index in range(nb)]
659
660 def descr_reduce(self, space):
661 result_w = [space.type(self)]
662
663 if self.iterators_w is not None:
664 iterators = [iterator if iterator is not None else space.newtuple([])
665 for iterator in self.iterators_w]
666 iterators = space.newtuple(iterators)
667 else:
668 iterators = space.newtuple([])
669 result_w = [space.type(self),
670 iterators,
671 self.w_fillvalue]
672 return space.newtuple(result_w)
673
674 def descr_setstate(self, space, w_state):
675 self.w_fillvalue = w_state
676
677 def iterator_greenkey(self, space):
678 # XXX in theory we should tupleize the greenkeys of all the
679 # sub-iterators, but much more work
680 if len(self.iterators_w) > 0:
681 return space.iterator_greenkey(self.iterators_w[0])
682 return None
683
684
685 def W_ZipLongest___new__(space, w_subtype, __args__):
686 arguments_w, kwds_w = __args__.unpack()
687 w_fillvalue = space.w_None
688 if kwds_w:
689 if "fillvalue" in kwds_w:
690 w_fillvalue = kwds_w["fillvalue"]
691 del kwds_w["fillvalue"]
692 if kwds_w:
693 raise oefmt(space.w_TypeError,
694 "zip_longest() got unexpected keyword argument(s)")
695
696 self = space.allocate_instance(W_ZipLongest, w_subtype)
697 self.__init__(space, space.w_None, arguments_w)
698 self.w_fillvalue = w_fillvalue
699 self.active = len(self.iterators_w)
700
701 return self
702
703 W_ZipLongest.typedef = TypeDef(
704 'itertools.zip_longest',
705 __new__ = interp2app(W_ZipLongest___new__),
706 __iter__ = interp2app(W_ZipLongest.iter_w),
707 __next__ = interp2app(W_ZipLongest.next_w),
708 __reduce__ = interp2app(W_ZipLongest.descr_reduce),
709 __setstate__ = interp2app(W_ZipLongest.descr_setstate),
710 __doc__ = """Return a zip_longest object whose .next() method returns a tuple where
711 the i-th element comes from the i-th iterable argument. The .next()
712 method continues until the longest iterable in the argument sequence
713 is exhausted and then it raises StopIteration. When the shorter iterables
714 are exhausted, the fillvalue is substituted in their place. The fillvalue
715 defaults to None or can be specified by a keyword argument.
716 """)
717
718
719 class W_Cycle(W_Root):
720 def __init__(self, space, w_iterable):
721 self.space = space
722 self.saved_w = []
723 self.w_iterable = space.iter(w_iterable)
724 self.index = 0 # 0 during the first iteration; > 0 afterwards
725
726 def iter_w(self):
727 return self
728
729 def next_w(self):
730 if self.index > 0:
731 if not self.saved_w:
732 raise OperationError(self.space.w_StopIteration, self.space.w_None)
733 try:
734 w_obj = self.saved_w[self.index]
735 except IndexError:
736 self.index = 1
737 w_obj = self.saved_w[0]
738 else:
739 self.index += 1
740 else:
741 try:
742 w_obj = self.space.next(self.w_iterable)
743 except OperationError as e:
744 if e.match(self.space, self.space.w_StopIteration):
745 self.index = 1
746 if not self.saved_w:
747 raise
748 w_obj = self.saved_w[0]
749 else:
750 raise
751 else:
752 self.saved_w.append(w_obj)
753 return w_obj
754
755 def descr_reduce(self, space):
756 # reduces differently than CPython 3.5. Unsure if it is a
757 # problem. To be on the safe side, keep three arguments for
758 # __setstate__; CPython takes two.
759 return space.newtuple([
760 space.type(self),
761 space.newtuple([self.w_iterable]),
762 space.newtuple([
763 space.newlist(self.saved_w),
764 space.newint(self.index),
765 # space.newbool(self.index > 0),
766 ]),
767 ])
768
769 def descr_setstate(self, space, w_state):
770 state_w = space.unpackiterable(w_state, 2)
771 w_saved = state_w[0]
772 self.saved_w = space.unpackiterable(w_saved)
773 w_index = state_w[1]
774 self.index = space.int_w(w_index)
775 # w_exhausted ignored
776 # w_exhausted = state_w[2]
777
778
779 def W_Cycle___new__(space, w_subtype, w_iterable, __posonly__, __args__):
780 w_type = space.gettypeobject(W_Cycle.typedef)
781 builtinclass_new_args_check(space, "cycle", w_type, w_subtype, __args__)
782 r = space.allocate_instance(W_Cycle, w_subtype)
783 r.__init__(space, w_iterable)
784 return r
785
786 W_Cycle.typedef = TypeDef(
787 'itertools.cycle',
788 __new__ = interp2app(W_Cycle___new__),
789 __iter__ = interp2app(W_Cycle.iter_w),
790 __next__ = interp2app(W_Cycle.next_w),
791 __reduce__ = interp2app(W_Cycle.descr_reduce),
792 __setstate__ = interp2app(W_Cycle.descr_setstate),
793 __doc__ = """Make an iterator returning elements from the iterable and
794 saving a copy of each. When the iterable is exhausted, return
795 elements from the saved copy. Repeats indefinitely.
796
797 Equivalent to :
798
799 def cycle(iterable):
800 saved = []
801 for element in iterable:
802 yield element
803 saved.append(element)
804 while saved:
805 for element in saved:
806 yield element
807 """)
808
809
810 class W_StarMap(W_Root):
811 def __init__(self, space, w_fun, w_iterable):
812 self.space = space
813 self.w_fun = w_fun
814 self.w_iterable = self.space.iter(w_iterable)
815
816 def iter_w(self):
817 return self
818
819 def next_w(self):
820 w_obj = self.space.next(self.w_iterable)
821 return self.space.call(self.w_fun, w_obj)
822
823 def descr_reduce(self):
824 return self.space.newtuple([self.space.gettypefor(W_StarMap),
825 self.space.newtuple([
826 self.w_fun,
827 self.w_iterable])
828 ])
829
830 def W_StarMap___new__(space, w_subtype, __args__):
831 args_w = W_Twoarg__new__(space, w_subtype, W_StarMap, "starmap", __args__)
832 r = space.allocate_instance(W_StarMap, w_subtype)
833 r.__init__(space, args_w[0], args_w[1])
834 return r
835
836 W_StarMap.typedef = TypeDef(
837 'itertools.starmap',
838 __new__ = interp2app(W_StarMap___new__),
839 __iter__ = interp2app(W_StarMap.iter_w),
840 __next__ = interp2app(W_StarMap.next_w),
841 __reduce__ = interp2app(W_StarMap.descr_reduce),
842 __doc__ = """Make an iterator that computes the function using arguments
843 tuples obtained from the iterable. Used instead of imap() when
844 argument parameters are already grouped in tuples from a single
845 iterable (the data has been ``pre-zipped''). The difference
846 between imap() and starmap() parallels the distinction between
847 function(a,b) and function(*c).
848
849 Equivalent to :
850
851 def starmap(function, iterable):
852 iterable = iter(iterable)
853 while True:
854 yield function(*iterable.next())
855 """)
856
857
858 @unwrap_spec(n=int)
859 def tee(space, w_iterable, n=2):
860 """Return n independent iterators from a single iterable.
861 Note : once tee() has made a split, the original iterable
862 should not be used anywhere else; otherwise, the iterable could get
863 advanced without the tee objects being informed.
864
865 Note : this member of the toolkit may require significant auxiliary
866 storage (depending on how much temporary data needs to be stored).
867 In general, if one iterator is going to use most or all of the
868 data before the other iterator, it is faster to use list() instead
869 of tee()
870
871 If iter(iterable) has no method __copy__(), this is equivalent to:
872
873 def tee(iterable, n=2):
874 def gen(next, data={}, cnt=[0]):
875 for i in count():
876 if i == cnt[0]:
877 item = data[i] = next()
878 cnt[0] += 1
879 else:
880 item = data[i] # data.pop(i) if it's the last one
881 yield item
882 it = iter(iterable)
883 return tuple([gen(it.next) for i in range(n)])
884
885 If iter(iterable) has a __copy__ method, though, we just return
886 a tuple t = (iterable, t[0].__copy__(), t[1].__copy__(), ...).
887 """
888 if n < 0:
889 raise oefmt(space.w_ValueError, "n must be >= 0")
890
891 w_iterator = space.iter(w_iterable)
892 if space.findattr(w_iterator, space.newtext("__copy__")) is not None:
893 # In this case, we don't instantiate any W_TeeIterable.
894 # We just rely on doing repeated __copy__(). This case
895 # includes the situation where w_iterable is already
896 # a W_TeeIterable itself.
897 iterators_w = [w_iterator] * n
898 for i in range(1, n):
899 iterators_w[i] = space.call_method(w_iterator, "__copy__")
900 else:
901 w_chained_list = W_TeeChainedListNode(space)
902 iterators_w = [W_TeeIterable(space, w_iterator, w_chained_list)
903 for x in range(n)]
904 return space.newtuple(iterators_w)
905
906 class W_TeeChainedListNode(W_Root):
907 def __init__(self, space):
908 self.w_next = None
909 self.w_obj = None
910 self.running = False
911
912 def reduce_w(self, space):
913 list_w = []
914 node = self
915 while node is not None and node.w_obj is not None:
916 list_w.append(node.w_obj)
917 node = node.w_next
918 if not list_w:
919 return space.newtuple([space.type(self), space.newtuple([])])
920 return space.newtuple(
921 [space.type(self),
922 space.newtuple([]),
923 space.newtuple([space.newlist(list_w)])
924 ])
925
926 def descr_setstate(self, space, w_state):
927 state = space.unpackiterable(w_state)
928 if len(state) != 1:
929 raise oefmt(space.w_ValueError, "invalid arguments")
930 obj_list_w = space.unpackiterable(state[0])
931 node = self
932 for w_obj in obj_list_w:
933 node.w_obj = w_obj
934 node.w_next = W_TeeChainedListNode(space)
935 node = node.w_next
936
937 def W_TeeChainedListNode___new__(space, w_subtype):
938 r = space.allocate_instance(W_TeeChainedListNode, w_subtype)
939 r.__init__(space)
940 return r
941
942 W_TeeChainedListNode.typedef = TypeDef(
943 'itertools._tee_dataobject',
944 __new__ = interp2app(W_TeeChainedListNode___new__),
945 __weakref__ = make_weakref_descr(W_TeeChainedListNode),
946 __reduce__ = interp2app(W_TeeChainedListNode.reduce_w),
947 __setstate__ = interp2app(W_TeeChainedListNode.descr_setstate)
948 )
949 W_TeeChainedListNode.typedef.acceptable_as_base_class = False
950
951 class W_TeeIterable(W_Root):
952 def __init__(self, space, w_iterator, w_chained_list=None):
953 self.space = space
954 self.w_iterator = w_iterator
955 self.w_chained_list = w_chained_list
956
957 def iter_w(self):
958 return self
959
960 def next_w(self):
961 w_chained_list = self.w_chained_list
962 if w_chained_list is None:
963 raise OperationError(self.space.w_StopIteration, self.space.w_None)
964 if w_chained_list.running:
965 raise oefmt(self.space.w_RuntimeError,
966 "cannot re-enter the tee iterator")
967 w_obj = w_chained_list.w_obj
968 if w_obj is None:
969 w_chained_list.running = True
970 try:
971 w_obj = self.space.next(self.w_iterator)
972 w_chained_list.running = False
973 except OperationError as e:
974 if e.match(self.space, self.space.w_StopIteration):
975 self.w_chained_list = None
976 w_chained_list.running = False
977 raise
978 w_chained_list.w_next = W_TeeChainedListNode(self.space)
979 w_chained_list.w_obj = w_obj
980 self.w_chained_list = w_chained_list.w_next
981 return w_obj
982
983 def copy_w(self):
984 space = self.space
985 tee_iter = W_TeeIterable(space, self.w_iterator, self.w_chained_list)
986 return tee_iter
987
988 def reduce_w(self):
989 return self.space.newtuple([self.space.gettypefor(W_TeeIterable),
990 self.space.newtuple([self.space.newtuple([])]),
991 self.space.newtuple([
992 self.w_iterator,
993 self.w_chained_list])
994 ])
995 def setstate_w(self, w_state):
996 state = self.space.unpackiterable(w_state)
997 num_args = len(state)
998 if num_args != 2:
999 raise oefmt(self.space.w_TypeError,
1000 "function takes exactly 2 arguments (%d given)",
1001 num_args)
1002 w_iterator, w_chained_list = state
1003 if not isinstance(w_chained_list, W_TeeChainedListNode):
1004 raise oefmt(self.space.w_TypeError,
1005 "must be itertools._tee_dataobject, not %s",
1006 self.space.type(w_chained_list).name)
1007
1008 self.w_iterator = w_iterator
1009 self.w_chained_list = w_chained_list
1010
1011 def W_TeeIterable___new__(space, w_subtype, w_iterable):
1012 if isinstance(w_iterable, W_TeeIterable):
1013 myiter = space.interp_w(W_TeeIterable, w_iterable)
1014 w_iterator = myiter.w_iterator
1015 w_chained_list = myiter.w_chained_list
1016 else:
1017 w_iterator = space.iter(w_iterable)
1018 w_chained_list = W_TeeChainedListNode(space)
1019 return W_TeeIterable(space, w_iterator, w_chained_list)
1020
1021 W_TeeIterable.typedef = TypeDef(
1022 'itertools._tee',
1023 __new__ = interp2app(W_TeeIterable___new__),
1024 __iter__ = interp2app(W_TeeIterable.iter_w),
1025 __next__ = interp2app(W_TeeIterable.next_w),
1026 __copy__ = interp2app(W_TeeIterable.copy_w),
1027 __weakref__ = make_weakref_descr(W_TeeIterable),
1028 __reduce__ = interp2app(W_TeeIterable.reduce_w),
1029 __setstate__ = interp2app(W_TeeIterable.setstate_w)
1030 )
1031 W_TeeIterable.typedef.acceptable_as_base_class = False
1032
1033
1034 class W_GroupBy(W_Root):
1035 def __init__(self, space, w_iterable, w_fun):
1036 self.space = space
1037 self.w_iterator = self.space.iter(w_iterable)
1038 if w_fun is None:
1039 w_fun = space.w_None
1040 self.w_keyfunc = w_fun
1041 self.w_tgtkey = None
1042 self.w_currkey = None
1043 self.w_currvalue = None
1044
1045 def iter_w(self):
1046 return self
1047
1048 def next_w(self):
1049 self.w_currgrouper = None
1050 self._skip_to_next_iteration_group()
1051 w_key = self.w_tgtkey = self.w_currkey
1052 w_grouper = W_GroupByIterator(self, w_key)
1053 return self.space.newtuple2(w_key, w_grouper)
1054
1055 def _skip_to_next_iteration_group(self):
1056 space = self.space
1057 while True:
1058 if self.w_currkey is None:
1059 pass
1060 elif self.w_tgtkey is None:
1061 break
1062 else:
1063 if not space.eq_w(self.w_tgtkey, self.w_currkey):
1064 break
1065
1066 w_newvalue = space.next(self.w_iterator)
1067 if space.is_w(self.w_keyfunc, space.w_None):
1068 w_newkey = w_newvalue
1069 else:
1070 w_newkey = space.call_function(self.w_keyfunc, w_newvalue)
1071
1072 self.w_currkey = w_newkey
1073 self.w_currvalue = w_newvalue
1074
1075 def descr_reduce(self, space):
1076 items_w = [space.type(self),
1077 space.newtuple([
1078 self.w_iterator,
1079 self.w_keyfunc])]
1080 if (self.w_tgtkey is not None and self.w_currkey is not None
1081 and self.w_currvalue is not None):
1082 items_w = items_w + [
1083 space.newtuple([
1084 self.w_currkey,
1085 self.w_currvalue,
1086 self.w_tgtkey])
1087 ]
1088 return space.newtuple(items_w)
1089
1090 def descr_setstate(self, space, w_state):
1091 state = space.unpackiterable(w_state)
1092 num_args = len(state)
1093 if num_args != 3:
1094 raise oefmt(space.w_TypeError,
1095 "function takes exactly 3 arguments (%d given)",
1096 num_args)
1097 self.w_currkey, self.w_currvalue, self.w_tgtkey = state
1098
1099 def W_GroupBy___new__(space, w_subtype, w_iterable, w_key=None):
1100 r = space.allocate_instance(W_GroupBy, w_subtype)
1101 r.__init__(space, w_iterable, w_key)
1102 return r
1103
1104 W_GroupBy.typedef = TypeDef(
1105 'itertools.groupby',
1106 __new__ = interp2app(W_GroupBy___new__),
1107 __iter__ = interp2app(W_GroupBy.iter_w),
1108 __next__ = interp2app(W_GroupBy.next_w),
1109 __reduce__ = interp2app(W_GroupBy.descr_reduce),
1110 __setstate__ = interp2app(W_GroupBy.descr_setstate),
1111 __doc__ = """Make an iterator that returns consecutive keys and groups from the
1112 iterable. The key is a function computing a key value for each
1113 element. If not specified or is None, key defaults to an identity
1114 function and returns the element unchanged. Generally, the
1115 iterable needs to already be sorted on the same key function.
1116
1117 The returned group is itself an iterator that shares the
1118 underlying iterable with groupby(). Because the source is shared,
1119 when the groupby object is advanced, the previous group is no
1120 longer visible. So, if that data is needed later, it should be
1121 stored as a list:
1122
1123 groups = []
1124 uniquekeys = []
1125 for k, g in groupby(data, keyfunc):
1126 groups.append(list(g)) # Store group iterator as a list
1127 uniquekeys.append(k)
1128 """)
1129
1130
1131 class W_GroupByIterator(W_Root):
1132 def __init__(self, groupby, w_tgtkey):
1133 self.groupby = groupby
1134 self.w_tgtkey = w_tgtkey
1135 groupby.w_currgrouper = self
1136
1137 def iter_w(self):
1138 return self
1139
1140 def next_w(self):
1141 groupby = self.groupby
1142 space = groupby.space
1143 if groupby.w_currgrouper is not self:
1144 raise OperationError(space.w_StopIteration, space.w_None)
1145 if groupby.w_currvalue is None:
1146 w_newvalue = space.next(groupby.w_iterator)
1147 if space.is_w(groupby.w_keyfunc, space.w_None):
1148 w_newkey = w_newvalue
1149 else:
1150 w_newkey = space.call_function(groupby.w_keyfunc, w_newvalue)
1151 #assert groupby.w_currvalue is None
1152 # ^^^ check disabled, see http://bugs.python.org/issue30347
1153 groupby.w_currkey = w_newkey
1154 groupby.w_currvalue = w_newvalue
1155
1156 assert groupby.w_currkey is not None
1157 if not space.eq_w(self.w_tgtkey, groupby.w_currkey):
1158 raise OperationError(space.w_StopIteration, space.w_None)
1159 w_result = groupby.w_currvalue
1160 groupby.w_currvalue = None
1161 groupby.w_currkey = None
1162 return w_result
1163
1164 def descr_reduce(self, space):
1165 if self.groupby.w_currgrouper is not self:
1166 w_callable = space.builtin.get('iter')
1167 return space.newtuple([w_callable, space.newtuple([space.newtuple([])])])
1168 return space.newtuple([
1169 space.type(self),
1170 space.newtuple([
1171 self.groupby,
1172 self.w_tgtkey]),
1173 ])
1174
1175 def W_GroupByIterator__new__(space, w_subtype, w_parent, w_tgtkey):
1176 r = space.allocate_instance(W_GroupByIterator, w_subtype)
1177 groupby = space.interp_w(W_GroupBy, w_parent)
1178 r.__init__(groupby, w_tgtkey)
1179 return r
1180
1181 W_GroupByIterator.typedef = TypeDef(
1182 'itertools._groupby',
1183 __new__ = interp2app(W_GroupByIterator__new__),
1184 __iter__ = interp2app(W_GroupByIterator.iter_w),
1185 __next__ = interp2app(W_GroupByIterator.next_w),
1186 __reduce__ = interp2app(W_GroupByIterator.descr_reduce))
1187 W_GroupByIterator.typedef.acceptable_as_base_class = False
1188
1189
1190 class W_Compress(W_Root):
1191 def __init__(self, space, w_data, w_selectors):
1192 self.space = space
1193 self.w_data = space.iter(w_data)
1194 self.w_selectors = space.iter(w_selectors)
1195
1196 def iter_w(self):
1197 return self
1198
1199 def next_w(self):
1200 # No need to check for StopIteration since either w_data
1201 # or w_selectors will raise this. The shortest one stops first.
1202 while True:
1203 w_next_item = self.space.next(self.w_data)
1204 w_next_selector = self.space.next(self.w_selectors)
1205 if self.space.is_true(w_next_selector):
1206 return w_next_item
1207
1208 def descr_reduce(self, space):
1209 return space.newtuple([
1210 space.type(self),
1211 space.newtuple([self.w_data, self.w_selectors])
1212 ])
1213
1214
1215 def W_Compress__new__(space, w_subtype, w_data, w_selectors):
1216 r = space.allocate_instance(W_Compress, w_subtype)
1217 r.__init__(space, w_data, w_selectors)
1218 return r
1219
1220 W_Compress.typedef = TypeDef(
1221 'itertools.compress',
1222 __new__ = interp2app(W_Compress__new__),
1223 __iter__ = interp2app(W_Compress.iter_w),
1224 __next__ = interp2app(W_Compress.next_w),
1225 __reduce__ = interp2app(W_Compress.descr_reduce),
1226 __doc__ = """Make an iterator that filters elements from *data* returning
1227 only those that have a corresponding element in *selectors* that evaluates to
1228 ``True``. Stops when either the *data* or *selectors* iterables has been
1229 exhausted.
1230 Equivalent to::
1231
1232 def compress(data, selectors):
1233 # compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
1234 return (d for d, s in zip(data, selectors) if s)
1235 """)
1236
1237
1238 class W_Product(W_Root):
1239 def __init__(self, space, args_w, w_repeat):
1240 self.gears = [
1241 space.unpackiterable(arg_w)[:] for arg_w in args_w
1242 ] * space.int_w(w_repeat)
1243 #
1244 for gear in self.gears:
1245 if len(gear) == 0:
1246 self.indices = None
1247 self.lst = None
1248 self.stopped = True
1249 break
1250 else:
1251 self.indices = [0] * len(self.gears)
1252 self.lst = None
1253 self.stopped = False
1254
1255 def _rotate_previous_gears(self):
1256 lst = self.lst
1257 x = len(self.gears) - 1
1258 assert x >= 0
1259 lst[x] = self.gears[x][0]
1260 self.indices[x] = 0
1261 x -= 1
1262 # the outer loop runs as long as a we have a carry
1263 while x >= 0:
1264 gear = self.gears[x]
1265 index = self.indices[x] + 1
1266 if index < len(gear):
1267 # no carry: done
1268 lst[x] = gear[index]
1269 self.indices[x] = index
1270 return
1271 lst[x] = gear[0]
1272 self.indices[x] = 0
1273 x -= 1
1274 else:
1275 self.lst = None
1276 self.stopped = True
1277
1278 def fill_next_result(self):
1279 # the last gear is done here, in a function with no loop,
1280 # to allow the JIT to look inside
1281 if self.lst is None:
1282 self.lst = [None for gear in self.gears]
1283 for index, gear in enumerate(self.gears):
1284 self.lst[index] = gear[0]
1285 return
1286 lst = self.lst
1287 x = len(self.gears) - 1
1288 if x >= 0:
1289 gear = self.gears[x]
1290 index = self.indices[x] + 1
1291 if index < len(gear):
1292 # no carry: done
1293 lst[x] = gear[index]
1294 self.indices[x] = index
1295 else:
1296 self._rotate_previous_gears()
1297 else:
1298 self.stopped = True
1299
1300 def iter_w(self, space):
1301 return self
1302
1303 def next_w(self, space):
1304 if not self.stopped:
1305 self.fill_next_result()
1306 if self.stopped:
1307 raise OperationError(space.w_StopIteration, space.w_None)
1308 w_result = space.newtuple(self.lst[:])
1309 return w_result
1310
1311 def descr_reduce(self, space):
1312 if not self.stopped:
1313 gears = [space.newtuple(gear) for gear in self.gears]
1314 result_w = [
1315 space.type(self),
1316 space.newtuple(gears)
1317 ]
1318 if self.lst is not None:
1319 indices_w = [space.newint(index) for index in self.indices]
1320 result_w = result_w + [space.newtuple(indices_w)]
1321 else:
1322 result_w = [
1323 space.type(self),
1324 space.newtuple([space.newtuple([])])
1325 ]
1326 return space.newtuple(result_w)
1327
1328 def descr_setstate(self, space, w_state):
1329 gear_count = len(self.gears)
1330 indices_w = space.unpackiterable(w_state)
1331 lst = []
1332 for i, gear in enumerate(self.gears):
1333 w_index = indices_w[i]
1334 index = space.int_w(w_index)
1335 gear_size = len(gear)
1336 if self.indices is None or gear_size == 0:
1337 self.stopped = True
1338 return
1339 if index < 0:
1340 index = 0
1341 if index > gear_size - 1:
1342 index = gear_size - 1
1343 self.indices[i] = index
1344 lst.append(gear[index])
1345 self.lst = lst
1346
1347 def W_Product__new__(space, w_subtype, __args__):
1348 arguments_w, kwds_w = __args__.unpack()
1349 w_repeat = space.newint(1)
1350 if kwds_w:
1351 if 'repeat' in kwds_w:
1352 w_repeat = kwds_w['repeat']
1353 del kwds_w['repeat']
1354 if kwds_w:
1355 raise oefmt(space.w_TypeError,
1356 "product() got unexpected keyword argument(s)")
1357
1358 r = space.allocate_instance(W_Product, w_subtype)
1359 r.__init__(space, arguments_w, w_repeat)
1360 return r
1361
1362 W_Product.typedef = TypeDef(
1363 'itertools.product',
1364 __new__ = interp2app(W_Product__new__),
1365 __iter__ = interp2app(W_Product.iter_w),
1366 __next__ = interp2app(W_Product.next_w),
1367 __reduce__ = interp2app(W_Product.descr_reduce),
1368 __setstate__ = interp2app(W_Product.descr_setstate),
1369 __doc__ = """
1370 Cartesian product of input iterables.
1371
1372 Equivalent to nested for-loops in a generator expression. For example,
1373 ``product(A, B)`` returns the same as ``((x,y) for x in A for y in B)``.
1374
1375 The nested loops cycle like an odometer with the rightmost element advancing
1376 on every iteration. This pattern creates a lexicographic ordering so that if
1377 the input's iterables are sorted, the product tuples are emitted in sorted
1378 order.
1379
1380 To compute the product of an iterable with itself, specify the number of
1381 repetitions with the optional *repeat* keyword argument. For example,
1382 ``product(A, repeat=4)`` means the same as ``product(A, A, A, A)``.
1383
1384 This function is equivalent to the following code, except that the
1385 actual implementation does not build up intermediate results in memory::
1386
1387 def product(*args, **kwds):
1388 # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
1389 # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
1390 pools = map(tuple, args) * kwds.get('repeat', 1)
1391 result = [[]]
1392 for pool in pools:
1393 result = [x+[y] for x in result for y in pool]
1394 for prod in result:
1395 yield tuple(prod)
1396 """)
1397
1398
1399 class W_Combinations(W_Root):
1400 def __init__(self, space, pool_w, indices, r):
1401 self.pool_w = pool_w
1402 self.indices = indices
1403 self.r = r
1404 self.last_result_w = None
1405 self.stopped = r > len(pool_w)
1406
1407 def get_maximum(self, i):
1408 return i + len(self.pool_w) - self.r
1409
1410 def max_index(self, j):
1411 return self.indices[j - 1] + 1
1412
1413 def descr__iter__(self, space):
1414 return self
1415
1416 def descr_next(self, space):
1417 if self.stopped:
1418 raise OperationError(space.w_StopIteration, space.w_None)
1419 if self.last_result_w is None:
1420 # On the first pass, initialize result tuple using the indices
1421 result_w = [None] * self.r
1422 for i in xrange(self.r):
1423 index = self.indices[i]
1424 result_w[i] = self.pool_w[index]
1425 else:
1426 # Copy the previous result
1427 result_w = self.last_result_w[:]
1428 # Scan indices right-to-left until finding one that is not at its
1429 # maximum
1430 i = self.r - 1
1431 while i >= 0 and self.indices[i] == self.get_maximum(i):
1432 i -= 1
1433
1434 # If i is negative, then the indices are all at their maximum value
1435 # and we're done
1436 if i < 0:
1437 self.stopped = True
1438 raise OperationError(space.w_StopIteration, space.w_None)
1439
1440 # Increment the current index which we know is not at its maximum.
1441 # Then move back to the right setting each index to its lowest
1442 # possible value
1443 self.indices[i] += 1
1444 for j in xrange(i + 1, self.r):
1445 self.indices[j] = self.max_index(j)
1446
1447 # Update the result for the new indices starting with i, the
1448 # leftmost index that changed
1449 for i in xrange(i, self.r):
1450 index = self.indices[i]
1451 w_elem = self.pool_w[index]
1452 result_w[i] = w_elem
1453 self.last_result_w = result_w
1454 return space.newtuple(result_w)
1455
1456 def descr_reduce(self, space):
1457 if self.stopped:
1458 pool_w = []
1459 else:
1460 pool_w = self.pool_w
1461 result_w = [
1462 space.type(self),
1463 space.newtuple([
1464 space.newtuple(pool_w), space.newint(self.r)
1465 ])]
1466 if self.last_result_w is not None and not self.stopped:
1467 # we must pickle the indices and use them for setstate
1468 result_w = result_w + [
1469 space.newtuple([
1470 space.newint(index) for index in self.indices])]
1471 return space.newtuple(result_w)
1472
1473 def descr_setstate(self, space, w_state):
1474 indices_w = space.fixedview(w_state)
1475 if len(indices_w) != self.r:
1476 raise oefmt(space.w_ValueError, "invalid arguments")
1477 for i in range(self.r):
1478 index = space.int_w(indices_w[i])
1479 max = self.get_maximum(i)
1480 # clamp the index (beware of negative max)
1481 if index > max:
1482 index = max
1483 if index < 0:
1484 index = 0
1485 self.indices[i] = index
1486 self.last_result_w = [
1487 self.pool_w[self.indices[i]]
1488 for i in range(self.r)]
1489
1490 @unwrap_spec(r=int)
1491 def W_Combinations__new__(space, w_subtype, w_iterable, r):
1492 pool_w = space.fixedview(w_iterable)
1493 if r < 0:
1494 raise oefmt(space.w_ValueError, "r must be non-negative")
1495 indices = range(r)
1496 res = space.allocate_instance(W_Combinations, w_subtype)
1497 res.__init__(space, pool_w, indices, r)
1498 return res
1499
1500 W_Combinations.typedef = TypeDef("itertools.combinations",
1501 __new__ = interp2app(W_Combinations__new__),
1502 __iter__ = interp2app(W_Combinations.descr__iter__),
1503 __next__ = interp2app(W_Combinations.descr_next),
1504 __reduce__ = interp2app(W_Combinations.descr_reduce),
1505 __setstate__ = interp2app(W_Combinations.descr_setstate),
1506 __doc__ = """\
1507 combinations(iterable, r) --> combinations object
1508
1509 Return successive r-length combinations of elements in the iterable.
1510
1511 combinations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3)""",
1512 )
1513
1514 class W_CombinationsWithReplacement(W_Combinations):
1515 def __init__(self, space, pool_w, indices, r):
1516 W_Combinations.__init__(self, space, pool_w, indices, r)
1517 self.stopped = len(pool_w) == 0 and r > 0
1518
1519 def get_maximum(self, i):
1520 return len(self.pool_w) - 1
1521
1522 def max_index(self, j):
1523 return self.indices[j - 1]
1524
1525 def descr_reduce(self, space):
1526 if self.stopped:
1527 pool_w = []
1528 else:
1529 pool_w = self.pool_w
1530 result_w = [
1531 space.type(self),
1532 space.newtuple([
1533 space.newtuple(pool_w), space.newint(self.r)
1534 ])]
1535 if self.last_result_w is not None and not self.stopped:
1536 # we must pickle the indices and use them for setstate
1537 result_w = result_w + [
1538 space.newtuple([
1539 space.newint(index) for index in self.indices])]
1540 return space.newtuple(result_w)
1541
1542 def descr_setstate(self, space, w_state):
1543 indices_w = space.fixedview(w_state)
1544 if len(indices_w) != self.r:
1545 raise oefmt(space.w_ValueError, "invalid arguments")
1546 for i in range(self.r):
1547 index = space.int_w(indices_w[i])
1548 max = self.get_maximum(i)
1549 # clamp the index (beware of negative max)
1550 if index > max:
1551 index = max
1552 if index < 0:
1553 index = 0
1554 self.indices[i] = index
1555 self.last_result_w = [
1556 self.pool_w[self.indices[i]]
1557 for i in range(self.r)]
1558
1559 @unwrap_spec(r=int)
1560 def W_CombinationsWithReplacement__new__(space, w_subtype, w_iterable, r):
1561 pool_w = space.fixedview(w_iterable)
1562 if r < 0:
1563 raise oefmt(space.w_ValueError, "r must be non-negative")
1564 indices = [0] * r
1565 res = space.allocate_instance(W_CombinationsWithReplacement, w_subtype)
1566 res.__init__(space, pool_w, indices, r)
1567 return res
1568
1569 W_CombinationsWithReplacement.typedef = TypeDef(
1570 "itertools.combinations_with_replacement",
1571 __new__ = interp2app(W_CombinationsWithReplacement__new__),
1572 __iter__ = interp2app(W_CombinationsWithReplacement.descr__iter__),
1573 __next__ = interp2app(W_CombinationsWithReplacement.descr_next),
1574 __reduce__ = interp2app(W_CombinationsWithReplacement.descr_reduce),
1575 __setstate__ = interp2app(W_CombinationsWithReplacement.descr_setstate),
1576 __doc__ = """\
1577 combinations_with_replacement(iterable, r) --> combinations_with_replacement object
1578
1579 Return successive r-length combinations of elements in the iterable
1580 allowing individual elements to have successive repeats.
1581 combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC""",
1582 )
1583
1584
1585 class W_Permutations(W_Root):
1586 def __init__(self, space, pool_w, r):
1587 self.pool_w = pool_w
1588 self.r = r
1589 n = len(pool_w)
1590 n_minus_r = n - r
1591 if n_minus_r < 0:
1592 self.stopped = self.raised_stop_iteration = True
1593 else:
1594 self.stopped = self.raised_stop_iteration = False
1595 self.indices = range(n)
1596 self.cycles = range(n, n_minus_r, -1)
1597 self.started = False
1598
1599 def descr__iter__(self, space):
1600 return self
1601
1602 def descr_next(self, space):
1603 if self.stopped:
1604 self.raised_stop_iteration = True
1605 raise OperationError(space.w_StopIteration, space.w_None)
1606 r = self.r
1607 indices = self.indices
1608 w_result = space.newtuple([self.pool_w[indices[i]]
1609 for i in range(r)])
1610 cycles = self.cycles
1611 i = r - 1
1612 while i >= 0:
1613 j = cycles[i] - 1
1614 if j > 0:
1615 cycles[i] = j
1616 indices[i], indices[-j] = indices[-j], indices[i]
1617 return w_result
1618 cycles[i] = len(indices) - i
1619 n1 = len(indices) - 1
1620 assert n1 >= 0
1621 num = indices[i]
1622 for k in range(i, n1):
1623 indices[k] = indices[k+1]
1624 indices[n1] = num
1625 i -= 1
1626 self.stopped = True
1627 if self.started:
1628 raise OperationError(space.w_StopIteration, space.w_None)
1629 else:
1630 self.started = True
1631 return w_result
1632
1633 def descr_reduce(self, space):
1634 if self.raised_stop_iteration:
1635 pool_w = []
1636 else:
1637 pool_w = self.pool_w
1638 result_w = [
1639 space.type(self),
1640 space.newtuple([
1641 space.newtuple(pool_w), space.newint(self.r)
1642 ])]
1643 if not self.raised_stop_iteration:
1644 # we must pickle the indices and use them for setstate
1645 result_w = result_w + [
1646 space.newtuple([
1647 space.newtuple([
1648 space.newint(index) for index in self.indices]),
1649 space.newtuple([
1650 space.newint(num) for num in self.cycles]),
1651 space.newbool(self.started)
1652 ])]
1653 return space.newtuple(result_w)
1654
1655 def descr_setstate(self, space, w_state):
1656 state = space.unpackiterable(w_state)
1657 if len(state) == 3:
1658 w_indices, w_cycles, w_started = state
1659 indices_w = space.unpackiterable(w_indices)
1660 cycles_w = space.unpackiterable(w_cycles)
1661 self.started = space.bool_w(w_started)
1662 else:
1663 raise oefmt(space.w_ValueError, "invalid arguments")
1664
1665 if len(indices_w) != len(self.pool_w) or len(cycles_w) != self.r:
1666 raise oefmt(space.w_ValueError, "inavalid arguments")
1667
1668 n = len(self.pool_w)
1669 for i in range(n):
1670 index = space.int_w(indices_w[i])
1671 if index < 0:
1672 index = 0
1673 elif index > n-1:
1674 index = n-1
1675 self.indices[i] = index
1676
1677 for i in range(self.r):
1678 index = space.int_w(cycles_w[i])
1679 if index < 1:
1680 index = 1
1681 elif index > n-i:
1682 index = n-i
1683 self.cycles[i] = index
1684
1685 def W_Permutations__new__(space, w_subtype, w_iterable, w_r=None):
1686 pool_w = space.fixedview(w_iterable)
1687 if space.is_none(w_r):
1688 r = len(pool_w)
1689 else:
1690 r = space.gateway_nonnegint_w(w_r)
1691 res = space.allocate_instance(W_Permutations, w_subtype)
1692 res.__init__(space, pool_w, r)
1693 return res
1694
1695 W_Permutations.typedef = TypeDef("itertools.permutations",
1696 __new__ = interp2app(W_Permutations__new__),
1697 __iter__ = interp2app(W_Permutations.descr__iter__),
1698 __next__ = interp2app(W_Permutations.descr_next),
1699 __reduce__ = interp2app(W_Permutations.descr_reduce),
1700 __setstate__ = interp2app(W_Permutations.descr_setstate),
1701 __doc__ = """\
1702 permutations(iterable[, r]) --> permutations object
1703
1704 Return successive r-length permutations of elements in the iterable.
1705
1706 permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)""",
1707 )
1708
1709
1710 class W_Accumulate(W_Root):
1711 'Return series of accumulated sums (or other binary function results).'
1712
1713 def __init__(self, space, w_iterable, w_func, w_initial):
1714 self.space = space
1715 self.w_iterable = w_iterable
1716 self.w_func = w_func if not space.is_w(w_func, space.w_None) else None
1717 self.w_total = None
1718 self.w_initial = w_initial
1719
1720 def iter_w(self):
1721 return self
1722
1723 def next_w(self):
1724 space = self.space
1725 if not space.is_w(self.w_initial, space.w_None):
1726 w_res = self.w_total = self.w_initial
1727 self.w_initial = space.w_None
1728 return w_res
1729 w_value = space.next(self.w_iterable)
1730 if self.w_total is None:
1731 self.w_total = w_value
1732 return w_value
1733
1734 if self.w_func is None:
1735 self.w_total = space.add(self.w_total, w_value)
1736 else:
1737 self.w_total = space.call_function(self.w_func, self.w_total, w_value)
1738 return self.w_total
1739
1740 def reduce_w(self):
1741 space = self.space
1742 w_func = space.w_None if self.w_func is None else self.w_func
1743 if not space.is_w(self.w_initial, space.w_None):
1744 w_it = W_Chain(space, space.iter(space.newlist([
1745 space.newtuple([self.w_initial]),
1746 self.w_iterable])))
1747 return space.newtuple([space.gettypefor(W_Accumulate),
1748 space.newtuple([w_it, w_func]),
1749 space.w_None])
1750 if self.w_total is space.w_None: # :-(
1751 w_it = W_Chain(space, space.iter(space.newlist([
1752 space.newtuple([self.w_total]),
1753 self.w_iterable])))
1754 w_it = space.call_function(space.type(self),
1755 w_it, w_func)
1756 return space.newtuple([space.gettypefor(W_ISlice),
1757 space.newtuple([w_it, space.newint(1),
1758 space.w_None])])
1759 w_total = space.w_None if self.w_total is None else self.w_total
1760 return space.newtuple([space.gettypefor(W_Accumulate),
1761 space.newtuple([self.w_iterable, w_func]), w_total])
1762
1763 def setstate_w(self, space, w_state):
1764 self.w_total = w_state if not space.is_w(w_state, space.w_None) else None
1765
1766 @unwrap_spec(w_initial=WrappedDefault(None))
1767 def W_Accumulate__new__(space, w_subtype, w_iterable, w_func=None, __kwonly__=None, w_initial=None):
1768 r = space.allocate_instance(W_Accumulate, w_subtype)
1769 r.__init__(space, space.iter(w_iterable), w_func, w_initial)
1770 return r
1771
1772 W_Accumulate.typedef = TypeDef("itertools.accumulate",
1773 __new__ = interp2app(W_Accumulate__new__),
1774 __iter__ = interp2app(W_Accumulate.iter_w),
1775 __next__ = interp2app(W_Accumulate.next_w),
1776 __reduce__ = interp2app(W_Accumulate.reduce_w),
1777 __setstate__ = interp2app(W_Accumulate.setstate_w),
1778 __doc__ = """\
1779 "accumulate(iterable) --> accumulate object
1780
1781 Return series of accumulated sums.""")
1782
1783
1784 class W_Pairwise(W_Root):
1785 'Return series of accumulated sums (or other binary function results).'
1786
1787 def __init__(self, space, w_iterator):
1788 self.space = space
1789 w_prev = None
1790 self.w_iterator = w_iterator
1791 self.w_prev = None
1792
1793 def iter_w(self):
1794 return self
1795
1796 def next_w(self):
1797 space = self.space
1798 w_prev = self.w_prev
1799 if w_prev is None:
1800 w_prev = space.next(self.w_iterator)
1801 self.w_prev = w_prev # set before fetching w_next to handle reentrancy
1802 w_next = space.next(self.w_iterator)
1803 self.w_prev = w_next
1804 return space.newtuple2(w_prev, w_next)
1805
1806 def W_Pairwise__new__(space, w_subtype, w_iterable, __posonly__=None):
1807 r = space.allocate_instance(W_Pairwise, w_subtype)
1808 r.__init__(space, space.iter(w_iterable))
1809 return r
1810
1811 W_Pairwise.typedef = TypeDef("itertools.pairwise",
1812 __new__ = interp2app(W_Pairwise__new__),
1813 __iter__ = interp2app(W_Pairwise.iter_w),
1814 __next__ = interp2app(W_Pairwise.next_w),
1815 __doc__ = """\
1816 Return an iterator of overlapping pairs taken from the input iterator.
1817
1818 s -> (s0, s1), (s1, s2), (s2, s3), ...
1819 """)