[Python-ideas] A different kind of context manager

Kristján Valur Jónsson kristjan at ccpgames.com
Wed Oct 23 16:24:54 CEST 2013


Syntax semantics stay the same.

Ø  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.
“Local” or “nonlocal” only has meaning within a function definition.  one that starts with “def function():”
I’m not suggesting new syntax. The code remains just a regular block, inside the “with” keyword and the variables there have the same binding as if the “with” statement were removed.  You are not defining a function, but the compiler _is_ producing a new kind of callable.  A “block” object, perhaps.  It might not _need_ to be technically a new kind of callable, perhaps such a block is implementable within the existing “function” type.  But that is merely an implementation detail.

My proposal thus has no changes on syntax, merely on how the block is invoked.  I suggest the code block be invoked explicitly by a “new-style context manager” rather than implicitly by the interpreter, inside the frame of __enter__/__exit__

K


From: Andrew Barnert [mailto:abarnert at yahoo.com]
Sent: 21. október 2013 23:37
To: Kristján Valur Jónsson
Cc: Chris Angelico; python-ideas
Subject: Re: [Python-ideas] A different kind of context manager

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/20131023/2b53f170/attachment-0001.html>


More information about the Python-ideas mailing list