PEP-able? Expressional conditions

Kay Schluehr kay.schluehr at gmx.net
Wed Sep 7 15:57:43 EDT 2005


Terry Reedy wrote:
> "Kay Schluehr" <kay.schluehr at gmx.net> wrote in message
> news:1126113430.910646.69290 at g44g2000cwa.googlegroups.com...
> > 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.
>
> By *carefully* using the flow-control operators 'and' and 'or', you can
> often get what you want *now*, no PEP required.
>
> > 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.
>
> *If* bool(result_expression_i) ==  True for all i, (except maybe last
> default expression), which is true for some actual use cases, then the
> following expression evaluates to the result corresponding to the first
> 'true' condition (if there is one) or to the default:
>
> c0 and r0 or c1 and r1 or c2 and r2... or default.
>
> I have only seen real examples with one and-pair, like (x < 0) and -x or x
> for absolute value.
>
> Terry J. Reedy

O.K. you win. One can complete this particular evaluation scheme by
introducing a little wrapper:

def Id(val):
    return lambda:val

(c0 and Id(r0) or c1 and Id(r1) or c2 and Id(r2)... or Id(default))()

This works for each sequence r0,r1,... without any restictions. 

Kay




More information about the Python-list mailing list