PEP-able? Expressional conditions
Kay Schluehr
kay.schluehr at gmx.net
Wed Sep 7 13:17:10 EDT 2005
Terry Hancock wrote:
> On Wednesday 07 September 2005 05:29 am, Kay Schluehr wrote:
> > Instead of pushing statements into expressions one can try to do it the
> > other way round and model expressions with the functionality of
> > statements.
>
> > Alternative syntax proposals:
> >
> > (a) (COND1,EXPR1) || (COND2,EXPR2)
> > (b) (COND1,EXPR1) case (COND2,EXPR2)
> > (c) (COND1,EXPR1) owise (COND2,EXPR2)
> > (d) (COND1,EXPR1) ? (COND2,EXPR2)
>
> You appear to be reinventing the C "ternary operator". This is
> definitely a dead horse. There was already a PEP, and it was
> refused.
Well, I'm not inspired by C and the operator is not ternary but binary
and associative. Nevertheless the behaviour of the ternary condition
operator exists as a limit case. The expression becomes more a kind of
a horizontal squeezed switch. Therefore the "case" keyword proposal.
It might become more obvious if one chains the expression using more
terms:
(a') (COND1,EXPR1) || (COND2,EXPR2) || ... || (CONDk,EXPRk)
(b') (COND1,EXPR1) case (COND2,EXPR2) case ... case (CONDk,EXPRk)
> If you actually want this, you're going to have to implement it
> with a function:
>
> def ternary(condition, true_result, false_result):
> if condition:
> return true_result
> else:
> return false_result
No, as I explained it is not a ternary operator and it can't easily be
implemented using a Python function efficiently because Python does not
support lazy evaluation. One usually does not want to evaluate all
conditions as well as all the results ( when passing them into the
function ) but evaluate conditional expressions sequentially and stop
at the first true condition. Well I would indeed like to go even
further and introduce lazy tuples this way but I wanted to notice the
responses to an obvious use case first.
Kay
More information about the Python-list
mailing list