PEP 308: Alternative conditional operator forms

Dave Brueck dave at pythonapocrypha.com
Tue Feb 11 16:48:44 EST 2003


On Tue, 11 Feb 2003, Michele Simionato wrote:

> > Out of curiosity, in what way is "if" overloaded? The reason I like 'if'
> > in this context is because it means the _exact_ same thing it does in an
> > if-statement: a condition is about to be checked in order to make a binary
> > desicion. Because it means the same thing as it does in an if-statement,
> > it's so much easier to guess the meaning if you're not familiar with it.
> >
> > The colon and (usually) indentation is what marks the beginning of a block
> > of code under an 'if', not the 'if' itself.
>
> As I said in some other thread, I want a clear distinction between the
> "if" statement and the conditional expression. They cannot be distinguished
> by a parenthesis only:
>
> if C: print x
> else: print y
>
> is correct whereas
>
> (if C: print x
>  else: print y)
>
> would be a syntax error!

Yes, but for at least two good reasons: multiline expressions in Python
require '\' to join the lines (and this shold be no exception) and 'print'
is a statement - there's no risk for hidden bugs because the code won't
even compile (and that's a good thing).

As to it would be confusing because they appear to differ only by parens,
you're leaving out the context in which they'd be used, and although the
parens are important, the actual context is even more important in
determining meaning. In an if-statement, the 'if' is what you see first.
Way, way, way on the other side of the spectrum you'd realistically never
see a conditional expression, in any of the proposed forms, as the first
thing on a line. The most common case is likely to be of the form:

x = (if ...)

So in reality there _is_ a clear distinction between the two.

> result = (if x==21: x*2 else: 42)
>
> And what is this with parens that has to be there? This is so
> inconsistent with how parens are used normally in Python. Normally they
> are only needed for tuples, functions and multiline statements.

... and emphasis/clarity and overriding precedence rules. This is how
they're used today and the above example is no exception.

> Moreover, I hate to call a function with
>
> f((if C: x else: y))

Me too. IIRC the "parens required" form is losing popularity anyway.

> C then x else y
>
> without parenthesis, colons, if and with "then" not a keyword ?

Hehehe... it turns out we agree more than not! I don't disagree with you
in that respect - the above is one of my favorites so far (I just didn't
find a problem using 'if' again)  and since the original PEP version is
losing favor I'll probably be casting my vote for the C then x else y
version. :)

-Dave





More information about the Python-list mailing list