python-trio / python-trio/trio

trio finalizes async gen functions without ResourceWarning on pypy - or if a strong reference is kept

Open
#2,378 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
7.3k
Forks
431
Avg merge
2d 17h
Merged PRs (30d)
6

Description

import trio

strong_references = set()

async def amain():
    print(f"{trio.lowlevel.current_task()=}")
    async def agen_fn():
        try:
            yield
        finally:
            print(f"{trio.lowlevel.current_task()=}")

    strong_references.add(agen := agen_fn())

    async for _ in agen:
        break

trio.run(amain)

output with python -W error demo.py:

trio.lowlevel.current_task()=<Task '__main__.amain' at 0x7fc7ff9cf2e0>
trio.lowlevel.current_task()=<Task '<init>' at 0x7fc7ff9cf240>

expected output:

trio.lowlevel.current_task()=<Task '__main__.amain' at 0x7fc7ff9cf2e0>
Exception ignored in: <async_generator object amain.<locals>.agen_fn at 0x7f75a13ef740>
Traceback (most recent call last):
  File "/home/graingert/projects/trio/trio/_core/_asyncgens.py", line 79, in finalizer
    warnings.warn(
ResourceWarning: Async generator '__main__.amain.<locals>.agen_fn' was garbage collected before it had been exhausted. Surround its use in 'async with aclosing(...):' to ensure that it gets cleaned up as soon as you're done using it.
trio.lowlevel.current_task()=<Task '<init>' at 0x7fc7ff9cf240>

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the provided demo with python -W error and compare the behavior on PyPy and when the async generator is strongly referenced. Then inspect trio/_core/_asyncgens.py, especially the finalizer around line 79. Done means the retained or PyPy-finalized unexhausted generator produces the expected ResourceWarning and finalization output.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.