if does not evaluate

Holger Türk htx1 at gmx.de
Sun Jun 6 11:13:02 CEST 2004



Tor Iver Wilhelmsen wrote:
> Jim Newton <jimka at rdrop.com> writes:
> 
> 
>>I.e.,  x = if something:
>>               expr1
>>            else:
>>               expr2
> 
> 
> Try exploiting that a boolean expression evaluates to 0 or 1:
> 
> x = (expr1, expr2)[something];

This is eagerly evaluated. If only one expression is meant to
be evaluated, the whole thing should look like this:

x = (lambda: expr1, lambda: expr2)[bool(something)]()

I added bool() to allow tests returning other values than
0 or 1.

Greetings,

Holger




More information about the Python-list mailing list