PyO3 / PyO3/pyo3

Support `__aenter__`/`__aexit__` for experimental-async coroutines

Open
#5,855 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Rust
Stars
16.2k
Forks
1k
Avg merge
2d 6h
Merged PRs (30d)
66

Description

Summary

We are using PyO3's experimental async support for coroutines, but currently, these coroutine objects do not support the async context manager protocol.

Because of this, we have to await the response first before we can use it in an async with block. The current code looks like this:

import asyncio
import rnet
from rnet import Response

async def main():
    # Currently, we must await the coroutine first separately
    resp: Response = await rnet.get("https://httpbin.io/stream/20")
    async with resp:
        async with resp.stream() as streamer:
            async for chunk in streamer:
                print(chunk)
                await asyncio.sleep(0.1)

if __name__ == "__main__":
    asyncio.run(main())

Expected Behavior

The expected usage should be much cleaner, allowing us to use async with directly on the awaited coroutine:

import asyncio
import rnet

async def main():
    # The goal is to support this one-liner pattern
    async with rnet.get("https://httpbin.io/stream/20") as resp:
        async with resp.stream() as streamer:
            async for chunk in streamer:
                print(chunk)
                await asyncio.sleep(0.1)

if __name__ == "__main__":
    asyncio.run(main())

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

No files or tests are identified in the issue. Start by locating PyO3's experimental-async coroutine implementation and its existing protocol support, then reproduce the documented examples; done means the coroutine returned by rnet.get can be used directly in an async with block while preserving the response streaming behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, rust
Domain
backend-api-design
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.