How yield catches StopIteration exception?

前端 未结 5 589
陌清茗
陌清茗 2020-12-08 04:54

Why in the example function terminates:

def func(iterable):
    while True:
        val = next(iterable)
        yield val

but if I take of

5条回答
  •  情深已故
    2020-12-08 05:20

    Tested on Python 3.8, chunk as lazy generator

    def split_to_chunk(size: int, iterable: Iterable) -> Iterable[Iterable]:
        source_iter = iter(iterable)
        while True:
            batch_iter = itertools.islice(source_iter, size)
            try:
                yield itertools.chain([next(batch_iter)], batch_iter)
            except StopIteration:
                return
    

    Why handling StopInteration error: https://www.python.org/dev/peps/pep-0479/

    def sample_gen() -> Iterable[int]:
        i = 0
        while True:
            yield i
            i += 1
    
    for chunk in split_to_chunk(7, sample_gen()):
        pprint.pprint(list(chunk))
        time.sleep(2)
    

    Output:

    [0, 1, 2, 3, 4, 5, 6]
    [7, 8, 9, 10, 11, 12, 13]
    [14, 15, 16, 17, 18, 19, 20]
    [21, 22, 23, 24, 25, 26, 27]
    ............................
    

提交回复
热议问题