[Python-Dev] PEP 550 v4

Koos Zevenhoven k7hoven at gmail.com
Thu Sep 7 07:04:54 EDT 2017


On Thu, Sep 7, 2017 at 10:54 AM, Greg Ewing <greg.ewing at canterbury.ac.nz>
wrote:

> Yury Selivanov wrote:
>
>>     def foo():
>>          var = ContextVar()
>>          var.set(1)
>>
>>     for _ in range(10**6): foo()
>>
>> If 'var' is strongly referenced, we would have a bunch of them.
>>
>
> Erk. This is not how I envisaged context vars would be
> used. What I thought you would do is this:
>
>    my_context_var = ContextVar()
>
>    def foo():
>       my_context_var.set(1)
>
> This problem would also not arise if context vars
> simply had names instead of being magic key objects:
>
>    def foo():
>       contextvars.set("mymodule.myvar", 1)
>
> That's another thing I think would be an improvement,
> but it's orthogonal to what we're talking about here
> and would be best discussed separately.
>
>
​​​There are lots of things in this discussion that I should have commented
on, but here's one related to this.

PEP 555 does not have the resource-management issue described above and
needs no additional tricks to achieve that:

# using PEP 555

def foo():
   var = contextvars.Var()
   with var.assign(1):
       # do something [*]

​for _ in range(10**6):
    foo(​)


Every time foo is called, a new context variable is created, but that's
perfectly fine, and lightweight. As soon as the context manager exits,
there are no references to the Assignment object returned by var.assign(1),
and as soon as foo() returns, there are no references to var, so everything
should get cleaned up nicely.

And regarding string keys, they have pros and cons, and they can be added
easily, so let's not go there now.

-- Koos


[*] (nit-picking) without closures that would keep the var reference alive


-- 
+ Koos Zevenhoven + http://twitter.com/k7hoven +
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20170907/8bb7e426/attachment.html>


More information about the Python-Dev mailing list