Itertools.islice currently raises
ValueError: Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize. when its
stop arguments are negative. However this requirement could be removed.
For example, by having a queue of items we can see n items into the future. This would allow us to determine whether we are within n items of the end of the iterable. Obviously this comes at the cost of having to queue up n items and so is impractical when
stop=-1_000_000, for example.
One prototype for this (this skips implementing the start and step arguments but these can be added) is:
def islice(iterable, stop): if stop >= 0: for index, item in enumerate(iterable): if index >= stop: break yield item else: # stop < 0 queue = collections.deque() iterable = iter(iterable) try: queue.extend(next(iterable) for _ in range(abs(stop))) except StopIteration: return for item in iterable: queue.append(item) yield queue.popleft()