Skip to content

Support __aenter__/__aexit__ for experimental-async coroutines #5855

@0x676e67

Description

@0x676e67

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())

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions