python / python/cpython

Support mixed sync and async context managers in `async with` statements

未关闭
#134,270 4 条评论 2 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

interpreter-core type-feature
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Over the last few years, I've found myself writing a lot of code which leans heavily on context managers, and parenthesized context managers make it quite conventient to do so - in all but one case. If you have mixed synchronous and async context managers, each switch from sync to async costs another level of indentation, making the code noticably harder to read.

I therefore propose that the async with statement should also accept mixed sync and async context managers, so long as there is at least one async context manager.


I've been using a helper function which gets most of the way towards this. I nonetheless think that the feature would be valuable, because:

  • It guides people away from a "convert to async cm" pattern (e.g. as_acm(sync_cm()) as v,), which changes code semantics by adding checkpoints where the async framework can switch tasks - and entering or exiting context managers is an unusally bad time to do that, since they are often responsible for timeouts or error handling.
  • Keeping the as clauses local helps to avoid naming confusion: when adding or deleting code, it's easy to mismatch async with multicontext(some(), contexts()) as (a, b): relative to async with some() as b, contexts as a:. As seen here, it's also more concise.
from contextlib import AsyncExitStack, asynccontextmanager

@asynccontextmanager
async def multicontext(*cms):
    assert any(hasattr(cm, "__aenter__") for cm in cms)
    async with AsyncExitStack() as stack:
        enter, aenter = stack.enter_context, stack.enter_async_context
        yield tuple(
            (enter(cm) if hasattr(cm, "__enter__") else await aenter(cm))
            for cm in cms
        )
Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere.

Update: now on discuss.python.org to collect feedback.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

issue 中没有指定源文件或测试。首先阅读提案和链接的 discuss.python.org 讨论串,然后确定允许混合同步和异步上下文管理器所需的语言语义和实现范围。语法和行为达成一致并由适当的测试覆盖后,即视为完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
compilers
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。