python / python/cpython

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

オープン
#134,270 コメント 4 件 リアクション 2 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

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. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

issue にはソースファイルもテストも記載されていません。まず提案とリンク先の discuss.python.org のスレッドを読み、同期および非同期のコンテキストマネージャーを混在させて使用できるようにするために必要な言語セマンティクスと実装範囲を特定してください。構文と動作について合意され、適切なテストでカバーされれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
compilers
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。