首页 > 解决方案 > 支持异步和同步调用的 Python 上下文管理器

问题描述

我正在构建一个使用工厂初始化/注入的上下文管理器,它创建资源实例,然后由上下文管理器管理。

我有两个不同的工厂:工厂 AsyncFactory

创建资源的标准版本的地方。另一个创建资源的异步版本。

目前我有两个上下文管理器:ContextManager 和 AsyncContextManager。在查看我的代码时,我知道上下文管理器init和 helper 函数在两种实现中都是相同的。

一种选择是创建一个 BaseContextManager,然后继承这个通用功能。

另一种方法是合并到一个上下文管理器中,该管理器同时具有enterexitaenteraexit方法实现。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”,它是否会以异步方式工作。

想知道人们对这种类型的上下文管理器的想法。我最初的感觉是让他们担任两个经理,以避免在一个班级做太多事情,但我对其他观点感兴趣。

标签: pythonasynchronouspython-asynciocontextmanager

解决方案


推荐阅读