[Python-ideas] PEP 525: Asynchronous Generators

Yury Selivanov yselivanov.ml at gmail.com
Wed Aug 24 15:14:25 EDT 2016


On 2016-08-16 12:46 PM, Moritz Sichert via Python-ideas wrote:

>>>> 2. It's extremely unlikely that somebody will design a system that
>>>> switches coroutine runners *while async/awaiting a coroutine*.
>>> Yes, I guess so.
>>>
>>>
>>>> But even in this unlikely use case, you can
>>>> easily stack finalizers following this pattern:
>>>>
>>>>     old_finalizer = sys.get_asyncgen_finalizer()
>>>>     sys.set_asyncgen_finalizer(my_finalizer)
>>>>     try:
>>>>       # do my thing
>>>>     finally:
>>>>       sys.set_asyncgen_finalizer(old_finalizer)
>>> That only works for synchronous code, though, because if this is done in a
>>> coroutine, it might get suspended within the try block and would leak its
>>> own finalizer into the outer world.
>> set_asyncgen_finalizer is designed to be used *only* by coroutine
>> runners.  This is a low-level API that coroutines should never
>> touch.  (At least my experience working with coroutines says so...)
> First of all, thanks for your work in this PEP! I think it really completes the
> async Python to a state where most synchronous code can be changed easily to be
> asynchronous.

Thank you!

[..]
> Now my questions:
> - Is it correct do check if the async iterator is actually a generator and only
> in that case do the whole get/set_asyncgen_finalizer() thing? As I understand,
> the finalizer is not needed for "normal" async iterators, i.e. instances of
> classes with a __anext__() method.

set_asyncgen_finalizer is only going to be used for native AG.

Asynchronous iterator objects implemented in pure Python, can
store a reference to the running loop and implement __del__
to do any kind of finalization.

> - Would it make sense to call sys.set_asyncgen_finalizer(old_finalizer) after
> the first call of async_iter.__anext__() instead of only at the end? As I
> understand the finalizer is set when the generator is started.
> - Is loop.run_until_complete(gen.aclose()) a sensible finalizer? If so, is there
> even any other finalizer that would make sense? Maybe creating a task for
> gen.aclose() instead of waiting for it to be completed?
Please read a new thread on python-dev.  I think it answers your
questions (in part) and asks a few more!

Thank you,
Yury



More information about the Python-ideas mailing list