On Thu, Sep 7, 2017 at 10:54 AM, Greg Ewing <greg.ew...@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 +
_______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com