相关文档:https://trio.readthedocs.io/en/latest/reference-core.html#synchronizing-and-communicating-between-tasks

相关代码:https://github.com/python-trio/trio/blob/master/trio/_channel.py

文档在close()个文档中提到"使用with receive_channel:将在离开With块时关闭频道对象".另一方面,演示该界面的文档的以下部分只使用async with receive_channel:,而close()个文档使用常规的with.

根据代码链接,相关类只有__enter____exit__,没有__aenter____aexit__.那么,为什么文档中的演示只使用了async with个?如果我在我的代码中使用常规的with,我是否会冒着将来的API更改 destruct 我的代码或类似的风险?

推荐答案

It seems this is to aid refactoring, and generally to promote loose coupling via dependency inversion.
The producer and consumer functions in the simple channel example from the docs do take an arbitrary SendChannel and ReceiveChannel respectively, not a memory channel specifically - admittedly it's hard to see given the lack of type annocations :-P

SendChannel/ReceiveChannel对象也实现AsyncResource接口,因此可以通过调用aclose或使用async with块来关闭它们.

你已经引用的documentation of MemoryReceiveChannel.close个国家明确表示

所有频道对象都有一个异步aclose方法.可以同步地关闭存储器通道also.

(emphasis mine)

因此,您可以使用普通的with块和close()方法来处理内存通道,没有 destruct API更改的风险.但是,如果您想要更改或重用您的代码来使用不同的通道实现,比如DTLSChannel或Web套接字,您首先会倾向于使用async with.

Python-3.x相关问答推荐

谁能解释一下这个带邮编的多功能环路?

如何使用魔杖扭曲图像

msg-seviri l1.5本机文件

Django 模型类方法使用错误的 `self`

使用 Python 在特定组的列中设置上限

Keras 中 Conv2D 层的意外结果

如何使用 regex sub 根据列表中的变量替换字符

在不使用字符串方法的情况下查找字符串最后一个单词的长度 - Python

Python3 AttributeError:列表对象没有属性清除

Await Future 来自 Executor:Future 不能在await表达式中使用

python3源的类图查看器应用程序

为什么 setattr 在绑定方法上失败

多个返回函数的列表理解?

为什么我在 Python 中收到错误消息无法导入名称 NoneType?

为什么中断比引发异常更快?

为 True 相交两个布尔数组

在没有时间的python中创建日期

没有名为urlparse的模块,但我没有使用 urlparse

三个参数的reduce函数

有效地判断一个元素是否在列表中至少出现 n 次