[Python-ideas] PEP draft: context variables

Koos Zevenhoven k7hoven at gmail.com
Mon Oct 9 16:39:49 EDT 2017


On Mon, Oct 9, 2017 at 6:24 PM, Guido van Rossum <guido at python.org> wrote:

> On Sun, Oct 8, 2017 at 11:46 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>
>> On 8 October 2017 at 08:40, Koos Zevenhoven <k7hoven at gmail.com> wrote:
>>
>>> On Sun, Oct 8, 2017 at 12:16 AM, Nathaniel Smith <njs at pobox.com> wrote:
>>>
>>>> On Oct 7, 2017 12:20, "Koos Zevenhoven" <k7hoven at gmail.com> wrote:
>>>>
>>>>
>>>> ​Unfortunately, we actually need a third kind of generator semantics,
>>>> something like this:
>>>>
>>>> @contextvars.caller_context
>>>> def genfunc():
>>>>     assert cvar.value is the_value
>>>>     yield
>>>>     assert cvar.value is the_value
>>>>
>>>> with cvar.assign(the_value):
>>>>     gen = genfunc()
>>>>
>>>> next(gen)
>>>>
>>>> with cvar.assign(1234567890):
>>>>     try:
>>>>         next(gen)
>>>>     except StopIteration:
>>>>         pass
>>>>
>>>> Nick, Yury and I (and Nathaniel, Guido, Jim, ...?) somehow just
>>>> narrowly missed the reasons for this in discussions related to PEP
>>>> 550. Perhaps because we had mostly been looking at it from an async angle.
>>>>
>>>>
>>>> That's certainly a semantics that one can write down (and it's what the
>>>> very first version of PEP 550 did),
>>>>
>>>
>>> ​​I do remember Yury mentioning that the first draft of PEP 550 captured
>>> something when the generator function was called. I think I started reading
>>> the discussions after that had already been removed, so I don't know
>>> exactly what it was. But I doubt that it was *exactly* the above, because
>>> PEP 550 uses set and get operations instead of "assignment contexts" like
>>> PEP 555 (this one) does. ​​
>>>
>>
>> We didn't forget it, we just don't think it's very useful.
>>
>
> I'm not sure I agree on the usefulness. Certainly a lot of the complexity
> of PEP 550 exists just to cater to Nathaniel's desire to influence what a
> generator sees via the context of the send()/next() call. I'm still not
> sure that's worth it. In 550 v1 there's no need for chained lookups.
>

​We do need some sort of chained lookups, though, at least in terms of
semantics. But it is possible to optimize that away in PEP 555. Some kind
of chained-lookup-like thing is inevitable if you want the state not to
leak though yields out of the generator:

with cvar.assign(a_value):
    # don't leak `a_value` to outer context
    yield some_stuff()


––Koos

-- 
+ Koos Zevenhoven + http://twitter.com/k7hoven +
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20171009/2c6de355/attachment.html>


More information about the Python-ideas mailing list