[New-bugs-announce] [issue44518] Finalization of non-exhausted asynchronous generators is deferred

Serhiy Storchaka report at bugs.python.org
Sun Jun 27 05:11:32 EDT 2021


New submission from Serhiy Storchaka <storchaka+cpython at gmail.com>:

In the following example:

def gen():
    try:
        yield 1
    finally:
        print('finalize inner')

def func():
    try:
        for x in gen():
            break
    finally:
        print('finalize outer')

func()
print('END')

the output in CPython is:

finalize inner
finalize outer
END


But in similar example for asynchronous generator:

async def gen():
    try:
        yield 1
    finally:
        print('finalize inner')

async def func():
    try:
        async for x in gen():
            break
    finally:
        print('finalize outer')

import asyncio
asyncio.run(func())
print('END')

the output in CPython is:

finalize outer
finalize inner
END

There is a strong link somewhere which prevents finalization of the asynchronous generator object until leaving the outer function.

Tested on CPython 3.7-3.11. In PyPy "finalize inner" is not printed at all. Using closing() and aclosing() is the right way to get deterministic finalization, but in any case it would be better to get rid of strong link which prevents finalization of the asynchronous generator object.

----------
components: Interpreter Core
messages: 396569
nosy: Mark.Shannon, asvetlov, gvanrossum, serhiy.storchaka, yselivanov
priority: normal
severity: normal
status: open
title: Finalization of non-exhausted asynchronous generators is deferred
type: resource usage
versions: Python 3.10, Python 3.11, Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44518>
_______________________________________


More information about the New-bugs-announce mailing list