python - 支持异步和同步调用的 Python 上下文管理器
问题描述
我正在构建一个使用工厂初始化/注入的上下文管理器,它创建资源实例,然后由上下文管理器管理。
我有两个不同的工厂:工厂 AsyncFactory
创建资源的标准版本的地方。另一个创建资源的异步版本。
目前我有两个上下文管理器:ContextManager 和 AsyncContextManager。在查看我的代码时,我知道上下文管理器init和 helper 函数在两种实现中都是相同的。
一种选择是创建一个 BaseContextManager,然后继承这个通用功能。
另一种方法是合并到一个上下文管理器中,该管理器同时具有enter、exit和aenter、aexit方法实现。IE
class ContextManager
def __init__(self, a, b, c)
...
def __enter__(self):
...
def __exit__(self):
...
def __aenter__(self):
...
def __aexit__(self):
...
def helper()
...
然后取决于是否称为“with”或“async with”,它是否会以异步方式工作。
想知道人们对这种类型的上下文管理器的想法。我最初的感觉是让他们担任两个经理,以避免在一个班级做太多事情,但我对其他观点感兴趣。
解决方案
推荐阅读
- excel - 将标准行/列中的 Excel 数据转换为每个唯一行 1 列,行数与列数一样多
- python-3.x - 有没有一种安全的方法可以从 Shell 脚本中杀死一个命名的 python 进程?
- reactjs - react native 中的 FlatList 正在渲染但不显示文本
- javascript - 在javascript(React)中使用特定键反转对象数组的问题
- r - 插入符号中带有 search = 'random' 选项的 tuneLength 参数不起作用
- javascript - 组件的多个导航链接使用 reactjs 呈现每次点击
- r - 是否有 R 函数来统计比较不同的集群解决方案?(例如,使用 pam/clara 解决方案的 k-means 解决方案)
- scala - 如何使用 Circe 解析动态 JSON
- javascript - 为什么没有为此 MediaStreamTrack 触发“结束”事件?
- azure - 如何使用 powershell 查询“Azure 状态”