[Python-ideas] If branch merging

Andrew Barnert abarnert at yahoo.com
Wed Jun 10 06:03:28 CEST 2015


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.

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.



More information about the Python-ideas mailing list