[Python-ideas] A different kind of context manager

Andrew Barnert abarnert at yahoo.com
Tue Oct 22 01:36:42 CEST 2013


On Oct 21, 2013, at 14:05, Kristján Valur Jónsson <kristjan at ccpgames.com> wrote:

> >And if you changed the rules so everything was nonlocal by default in a context function, we'd need a new keyword to declare local variables, which would be (a) very different from the > rest of python, and (b) hard to come up with a name for that didn't conflict with thousands of different programs.
> 
>  
> 
> Well no.  You are not defining a function, so all variables are in the same scope as the existing code.  Binding does not change.  “nonlocal” has exactly the same meaning, meaning outside the function you are writing.  The “anonymous callable” exists only technically, not syntactically.  It has no local variables, no (visible) arguments.
> 
> Semantics stay exactly the same, only the method of invoking the executable code changes.
> 
Obviously semantics don't stay exactly the same or there would be no benefits to the change. The whole point is that you're creating a function with closure and visibly passing it to a method of the context manager.

It's either one or the other: either every variable is implicitly nonlocal whether you want it to be or not, or every variable is implicitly local and you have to nonlocal them to perform common context manager idioms.

Compare with comprehensions. Changing them to use functions under the covers had no effect (other than breaking a rare use case with StopIteration passing, which I believe has been fixed), but that's only because the comprehension variable(s) were already explicitly prevented from replacing existing bindings. (The fact that there's no way to explicitly bind a variable in a comprehension helps too--no potential surprised about what "x=2" might do when statements aren't allowed in the first place.) That's obviously not true for with statements.

If you think that every variable being implicitly nonlocal is a good thing, that's certainly arguable (maybe no existing code would ever notice the difference, and new code that did wouldn't be surprised by it?), but only of you make that case instead of trying to argue that there isn't an issue in the first place.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20131021/b3af62dc/attachment-0001.html>


More information about the Python-ideas mailing list