bpo-33786: Fix asynchronous generators to handle GeneratorExit in athrow() by 1st1 · Pull Request #7467 · python/cpython (original) (raw)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As far as I understand, this will make .aclose() raise StopIteration in the usual case (when generator doesn't handle the GeneratorExit).

Keep in mind, that raising StopIteration from any of a***() methods just means that they are returning. They are all iterators.

What about .athrow(), how will it behave?

The idea here:

  1. athrow() and aclose() share one implementation.
  2. aclose() is basically an athrow(GeneratorExit).
  3. When aclose() is called and the generator propagates GeneratorExit, it means that everything is fine and the aclose() call was successful. We raise StopIteration to make aclose() awaitable return.
  4. When athrow() is called we don't want to trap any exceptions at all. So we raise StopIteration only if the asynchronous generator swallowed the thrown error and yielded (asynchronously).

This is a bit complex, I know. I explained how asynchronous generators work in detail here: https://www.python.org/dev/peps/pep-0525/#implementation-details