[Python-ideas] If branch merging
Chris Angelico
rosuav at gmail.com
Wed Jun 10 08:17:21 CEST 2015
On Wed, Jun 10, 2015 at 2:03 PM, Andrew Barnert <abarnert at yahoo.com> wrote:
> On Jun 9, 2015, at 20:27, Chris Angelico <rosuav at gmail.com> wrote:
>>
>>
>> with open("spam.log", "a") as logfile:
>> def log(x):
>> logfile.write(x)
>>
>> Given that this example wouldn't work anyway (the file would get
>> closed before the function gets called), and I can't think of any
>> non-trivial examples where you'd actually want this, I can't call what
>> ought to happen.
>
> The obvious one is:
>
> with open("spam.log", "a") as logfile:
> def log(x):
> logfile.write(x)
> do_lots_of_stuff(logfunc=log)
>
> Of course in this case you could just pass logfile.write instead of a function, but more generally, anywhere you create a helper or callback as a closure to use immediately (e.g., in a SAX parser) instead of later (e.g., in a network server or GUI) it makes sense to put a closure inside a with statement.
>
Sure. In this example, there'd have to be some kind of "thing" that
exists as a global, and can be referenced by the log function. That's
not too hard; the usage all starts and ends inside the duration of the
"as" effect; any other global named "logfile" would simply be
unavailable. The confusion would come if you try to span the boundary
in some way - when it would be possible to call log(logfile) and have
it write to the log file defined by the with block, but have its
argument come from outside.
At very least, that would want to be strongly discouraged for reasons
of readability.
> Also, remember that the whole point here is to extend as-binding so it works in if and while conditions, and maybe arbitrary expressions, and those cases it's even more obvious why you'd want to create a closure.
>
> Anyway, I think I know what all the compiled bytecode and code attributes for that case could look like (although I'd need to think through the edge cases), I'm just not sure if the code that compiles it today will be able to handle things without some rename-and-rename-back hack. I suppose the obvious answer is for someone to just try writing it and see. :)
>
> But I think your quick&dirty hack may be worth playing with even if it bans this possibility and a few others, and may not be that hard to do if you make that decision, so if I were you I'd try that first.
>
Okay. I'll start poking around with CPython and see what I can do.
I'm reminded of that spectacular slide from David Beazley's talk on
CPython and PyPy tinkering, where he has that VW called CPython, and
then talks about patches, extensions, PEPs... and python-ideas.
https://www.youtube.com/watch?v=l_HBRhcgeuQ at the four minute mark.
ChrisA
More information about the Python-ideas
mailing list