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

Improvecontextlib.ContextDecorator support for generators and async functions #125862

Open
Labels
stdlibPython modules in the Lib dirtype-featureA feature request or enhancement
@Zac-HD

Description

@Zac-HD

Suppose we define a context manager, in the usual way:

@contextmanagerdefctx():print("enter")yieldprint("exit")defclassic():withctx():print("body")classic()# enter, body, exit

We can also use it as a decorator, thanks to theconvenientContextDecorator class used by@contextmanager:

@ctx()deffn():print("body")fn()# enter, body, exit

...but if we naively do the same thing to a generator or an async function, the equivalence breaks down:

@ctx()defgen():print("body")yieldfor_ingen(): ...# enter, exit, body!@ctx()asyncdefafn():print("body")awaitafn()# enter, exit, body!

This seems pretty obviously undesirable, so I think we'll want to changeContextDecorator.__call__. Possibilities include:

  1. branch on iscoroutinefunction / isgeneratorfunction / isasyncgenfunction, creating alternativeinner functions to preserve the invariant that@ctx() is just like writingwith ctx(): as the first line of the function body. In a quick survey, this is the expected behavior, but also a change from the current effect of the decorator.

  2. instead of branching, warn (and after a few years raise) when decorating a generator or async function.

    • alternative implementation: inspect the return value insideinner, to detect sync wrappers of async functions. I think the increased accuracy is unlikely to be worth the performance cost.
    • we could retain the convenience of using a decorator by definingContextDecorator.gen(),.async_(), and.agen() methods which explicitly support wrapping their corresponding kind of function.

We'll also want applying anAsyncContextDecorator to an async generator function to match whatever we decide forContextDecorator on a sync generator.

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-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