Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Support mixed sync and async context managers inasync with statements #134270

Open
Labels
interpreter-core(Objects, Python, Grammar, and Parser dirs)type-featureA feature request or enhancement
@Zac-HD

Description

@Zac-HD

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 theasync 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 theas clauses local helps to avoid naming confusion: when adding or deleting code, it's easy to mismatchasync with multicontext(some(), contexts()) as (a, b): relative toasync with some() as b, contexts as a:. As seen here, it's also more concise.
fromcontextlibimportAsyncExitStack,asynccontextmanager@asynccontextmanagerasyncdefmulticontext(*cms):assertany(hasattr(cm,"__aenter__")forcmincms)asyncwithAsyncExitStack()asstack:enter,aenter=stack.enter_context,stack.enter_async_contextyieldtuple(            (enter(cm)ifhasattr(cm,"__enter__")elseawaitaenter(cm))forcmincms        )

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp