[Python-ideas] PEP draft: context variables

Steve Dower steve.dower at python.org
Fri Oct 13 18:44:02 EDT 2017


On 13Oct2017 1132, Yury Selivanov wrote:
> On Fri, Oct 13, 2017 at 1:45 PM, Ethan Furman <ethan at stoneleaf.us> wrote:
>> On 10/13/2017 09:48 AM, Steve Dower wrote:
>>>
>>> On 13Oct2017 0941, Yury Selivanov wrote:
>>
>>
>>>> Actually, capturing context at the moment of coroutine creation (in
>>>> PEP 550 v1 semantics) will not work at all.  Async context managers
>>>> will break.
>>>>
>>>>      class AC:
>>>>          async def __aenter__(self):
>>>>               pass
>>>>
>>>> ^ If the context is captured when coroutines are instantiated,
>>>> __aenter__ won't be able to set context variables and thus affect the
>>>> code it wraps.  That's why coroutines shouldn't capture context when
>>>> created, nor they should isolate context.  It's a job of async Task.
>>>
>>>
>>> Then make __aenter__/__aexit__ when called by "async with" an exception to
>>> the normal semantics?
>>>
>>> It seems simpler to have one specially named and specially called function
>>> be special, rather than make the semantics
>>> more complicated for all functions.
>>
> 
> It's not possible to special case __aenter__ and __aexit__ reliably
> (supporting wrappers, decorators, and possible side effects).

Why not? Can you not add a decorator that sets a flag on the code object 
that means "do not create a new context when called", and then it 
doesn't matter where the call comes from - these functions will always 
read and write to the caller's context. That seems generally useful 
anyway, and then you just say that __aenter__ and __aexit__ are special 
and always have that flag set.

>> +1.  I think that would make it much more usable by those of us who are not
>> experts.
> 
> I still don't understand what Steve means by "more usable", to be honest.

I don't know that I said "more usable", but it would certainly be easier 
to explain. The Zen has something to say about that...

Cheers,
Steve


More information about the Python-ideas mailing list