[Python-Dev] Multiline with statement line continuation

Steven D'Aprano steve at pearwood.info
Sat Aug 16 13:16:52 CEST 2014


On Sat, Aug 16, 2014 at 05:25:33PM +1000, Ben Finney wrote:
[...] 
> > they would have already mistaken:
> >
> >     with a, b, c: ...
> >
> > the same way. But they haven't.
> 
> Right. The presence or absence of parens make a big semantic difference.

from silly.mistakes.programmers.make import (
     hands, up, anyone, who, thinks, this, is_, a, tuple)

def function(how, about, this, one): ...


But quite frankly, even if there is some person somewhere who gets 
confused and tries to write:

context_managers = (open("a"), open("b", "w"), open("c", "w"))
with context_managers as things:
    text = things[0].read()
    things[1].write(text)
    things[2].write(text.upper())


I simply don't care. They will try it, discover that tuples are not 
context managers, fix their code, and move on. (I've made sillier 
mistakes, and became a better programmer from it.)

We cannot paralyse ourselves out of fear that somebody, somewhere, will 
make a silly mistake. You can try that "with tuple" code right now, and 
you will get nice runtime exception. I admit that the error message is 
not the most descriptive I've ever seen, but I've seen worse, and any 
half-decent programmer can do what they do for any other unexpected 
exception: read the Fine Manual, or ask for help, or otherwise debug the 
problem. Why should this specific exception be treated as so harmful 
that we have to forgo a useful piece of functionality to avoid it?

Some designs are bug-magnets, like the infamous "except A,B" syntax, 
which fails silently, doing the wrong thing. Unless someone has a 
convincing rationale for how and why this multi-line with will likewise 
be a bug-magnet, I don't think that some vague similarity between it and 
tuples is justification for rejecting the proposal.


-- 
Steven


More information about the Python-Dev mailing list