[Python-ideas] PEP draft: context variables

Yury Selivanov yselivanov.ml at gmail.com
Fri Oct 13 11:41:28 EDT 2017


On Fri, Oct 13, 2017 at 3:25 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
[..]
> The rationale for this behaviour *does* arise from a refactoring argument:
>
>    async def original_async_function():
>         with some_context():
>             do_some_setup()
>             raw_data = await some_operation()
>             data = do_some_postprocessing(raw_data)
>
> Refactored:
>
>    async def async_helper_function():
>         do_some_setup()
>         raw_data = await some_operation()
>         return do_some_postprocessing(raw_data)
>
>    async def refactored_async_function():
>         with some_context():
>             data = await async_helper_function()
>
> However, considering that coroutines are almost always instantiated at the
> point where they're awaited,

"almost always"  is an incorrect assumption. "usually" would be the correct one.

> I do concede that creation time context capture
> would likely also work out OK for the coroutine case, which would leave
> contextlib.contextmanager as the only special case (and it would turn off
> both creation-time context capture *and* context isolation).

I still believe that both versions of PEP 550 (v1 & latest) got this right:

* Coroutines on their own don't capture context;
* Tasks manage context for coroutines they wrap.

Yury


More information about the Python-ideas mailing list