What is the difference between raise StopIteration and a return statement in generators?

前端 未结 3 1347
误落风尘
误落风尘 2020-12-08 13:08

I\'m curious about the difference between using raise StopIteration and a return statement in generators.

For example, is there any differe

3条回答
  •  星月不相逢
    2020-12-08 14:05

    As of late 2014 return is correct and raise StopIteration for ending a generator is on a depreciation schedule. See PEP 479 for full details.

    Abstract

    This PEP proposes a change to generators: when StopIteration is raised inside a generator, it is replaced with RuntimeError. (More precisely, this happens when the exception is about to bubble out of the generator's stack frame.) Because the change is backwards incompatible, the feature is initially introduced using a __future__ statement.

    Acceptance

    This PEP was accepted by the BDFL on November 22…

    Rationale

    The interaction of generators and StopIteration is currently somewhat surprising, and can conceal obscure bugs. An unexpected exception should not result in subtly altered behaviour, but should cause a noisy and easily-debugged traceback. Currently, StopIteration raised accidentally inside a generator function will be interpreted as the end of the iteration by the loop construct driving the generator.

提交回复
热议问题