Difference between Python's Generators and Iterators

后端 未结 11 1332
谎友^
谎友^ 2020-11-22 05:20

What is the difference between iterators and generators? Some examples for when you would use each case would be helpful.

11条回答
  •  执念已碎
    2020-11-22 05:46

    Previous answers missed this addition: a generator has a close method, while typical iterators don’t. The close method triggers a StopIteration exception in the generator, which may be caught in a finally clause in that iterator, to get a chance to run some clean‑up. This abstraction makes it most usable in the large than simple iterators. One can close a generator as one could close a file, without having to bother about what’s underneath.

    That said, my personal answer to the first question would be: iteratable has an __iter__ method only, typical iterators have a __next__ method only, generators has both an __iter__ and a __next__ and an additional close.

    For the second question, my personal answer would be: in a public interface, I tend to favor generators a lot, since it’s more resilient: the close method an a greater composability with yield from. Locally, I may use iterators, but only if it’s a flat and simple structure (iterators does not compose easily) and if there are reasons to believe the sequence is rather short especially if it may be stopped before it reach the end. I tend to look at iterators as a low level primitive, except as literals.

    For control flow matters, generators are an as much important concept as promises: both are abstract and composable.

提交回复
热议问题