For review: PEP 308 - If-then-else expression

Paul Rubin phr-n2003b at NOSPAMnightsong.com
Fri Feb 7 14:14:00 EST 2003


Guido van Rossum <guido at python.org> writes:
>     Requests for an if-then-else ("ternary") expression keep coming up
>     on comp.lang.python.  This PEP contains a concrete proposal of a
>     fairly Pythonic syntax.  This is the community's one chance: if
>     this PEP is approved with a clear majority, it will be implemented
>     in Python 2.4.  If not, the PEP will be augmented with a summary
>     of the reasons for rejection and the subject better not come up
>     again.  While I am the author of this PEP, I am neither in favor
>     nor against this proposal; it is up to the community to decide.
>     If the community can't decide, I'll reject the PEP.

Sounds fair.

> Proposal
> 
>     The proposed syntax is as follows:
> 
>         <expression1> if <condition> else <expression2>

I have to say this sounds excessively Perlish, putting the condition
after the first expression like that.

>     Many C-derived languages use this syntax:
> 
>         <condition> ? <expression1> : <expression2>
> 
>     I reject this for several reasons: the colon already has many uses
>     in Python (even though it would actually not be ambiguous, because
>     the question mark requires a matching colon); for people not used
>     to C-derived language, it is hard to understand.

If the use of the colon is consistent with other ways Python uses
colon, then using it in conditional expressions seems ok.  I
personally don't have a problem with using question mark (I don't
remember having any trouble understanding it when I first encountered
it in C) but I agree that it's not so Pythonic.

Adding a keyword doesn't seem to me like a big problem, unless it's a
keyword that will break a lot of programs (e.g. don't use "n" as a
keyword).  So here's another alternative:

    ifelse condition: expression1 else: expression2

or if the word "ifelse" is too ugly, we could use a different one instead,
like maybe "select".

The else clause could be chainable with elif:

    ifelse cond1: exp1 elif cond2: exp2 else: exp3

Hopefully that wouldn't get used too frequently, but it does sometimes
turn out useful to have several nested ?: expressions in C programs.

In the many threads that have gone by on this subject in the past,
there's been several other good suggestions.  Maybe some of those can
be dug up and posted to this thread.




More information about the Python-list mailing list