Proposed PEP for a Conditional Expression
Bernhard Herzog
bh at intevation.de
Mon Sep 10 06:19:11 EDT 2001
Michael Chermside <mcherm at destiny.com> writes:
Good summary of the arguments usually made for or agains conditional
operators!
> WORKAROUND_1: (this fails)
> > def cond(c, a, b):
> > if c: return a
> > else: return b
> > x = cond(c, a, b)
> This fails, because it does not short-circuit...
It also fails because of inconsistent indentation :)
> ARG_23: Lots of people ask for it.
> Lots of people ask for a conditional expression. Even if the
> other pro arguments don't convince you, what harm is there in
> settling this one? For a LONG time, we used to hear
> complaints about how Python lacked "+=", "*=" and such; now
> that it has them, the complaints have died to a trickle.
> What's wrong with just satisfying people?
Lots of people asking for it is a reason to write the PEP, but not
necessarily a reason to actually adopt the PEP.
> SPEC_1: Use the "C syntax".
> The following production would be added to Python syntax:
> expression: expression ? exprression : expression
> Since "?" is not currently used in Python, this would never
> be syntactically ambiguous. Sample: a = b ? c : d
>
> PRO - [familiar to programmers]
But only to programmers coming from "C-like" languages.
> SPEC_2: Use "if-then-else".
[...]
> SPEC_3: Use "if-then-else" without keyword.
[...]
These are the best spellings for this, I think.
Another way that come to mind:
<expr> if <cond> else <expr>
The order in which the condition and the braches occur is unusual for
python, but this spelling has the advantage of not needing an additional
keyword or colons.
> SPEC_4: Use "if c: a else: b".
> The following production would be added to Python syntax:
> expression: "if" expression ":" expression "else" ":"
> expression
> The famous "dangling-else" problem would NOT arise because
> the "else:" part would be mandatory.
I think this would look better without the colon after the else. I'm not
sure why though.
Bernhard
--
Intevation GmbH http://intevation.de/
Sketch http://sketch.sourceforge.net/
MapIt! http://mapit.de/
More information about the Python-list
mailing list