agronholm / agronholm/anyio

add an AnyIO equivalent of trio.as_safe_channel

未關閉
#1,192 3 則留言 4 個 reaction 已指派 0 人 在 GitHub 檢視
enhancement
主要語言
Python
星號
2.5k
分支
260
平均合併
1 天 8 小時
30 天內合併 PR
17

描述

### Things to check first

- [x] I have searched the existing issues and didn't find my feature already requested there

### Feature description

trio has https://trio.readthedocs.io/en/stable/reference-core.html#trio.as_safe_channel we should add an anyio.as_safe_memory_object_stream

### Use case

From the trio docs:

The yield keyword offers a very convenient way to write iterators… which makes it really unfortunate that async generators are so difficult to call correctly. Yielding from the inside of a cancel scope or a nursery to the outside violates structured concurrency with consequences explained in PEP 789. Even then, resource cleanup errors remain common (PEP 533) unless you wrap every call in aclosing().

This decorator gives you the best of both worlds: with careful exception handling and a background task we preserve structured concurrency by offering only the safe interface, and you can still write your iterables with the convenience of yield. For example:

```py
@as_safe_channel
async def my_async_iterable(arg, *, kwarg=True):
while ...:
item = await ...
yield item

async with my_async_iterable(...) as recv_chan:
async for item in recv_chan:
...
```

# notes

This should be in core AnyIO because it requires private access to send_stream._state.open_receive_channels

貢獻指南

開啟貢獻指南

評估

這個 Issue 還沒有評估資料。

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。