Re: Is there something similar to ?: operator (C/C++) in Python?
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: Is there something similar to ?: operator (C/C++) in Python?

From: Ron Adam <rrr@ronadam.com>
Date: Thu Jun 30 2005 - 20:19:26 CEST

Antoon Pardon wrote:
> Op 2005-06-29, Scott David Daniels schreef <Scott.Daniels@Acm.Org>:
>
>>Roy Smith wrote:
>>
>>>Andrew Durdin <adurdin@gmail.com> wrote:
>>>
>>>>Corrected version:
>>>> result = [(lambda: expr0), lambda: expr1][bool(cond)]()
>>
>>Sorry, I thought cond was a standard boolean.
>>Better is:
>> result = [(lambda: true_expr), lambda: false_expr][not cond]()
>
>
> How about the following:
>
> result = (cond and (lambda: true_expr) or (lambda: false_expr))()
>

That works as long as long as they are expressions, but the ? format
does seem to be more concise I admit.

To use *any* expressions in a similar way we need to use eval which is a
lot slower unfortunately.

    result = eval(['expr0','expr1'][cond])

A thought occurs to me that putting index's before the list might be an
interesting option for expressions.

    result = expr[expr0,expr1]

This would probably conflict with way too many other things though.
Maybe this would be better?

    result = index from [expr0,expr1]

Where index can be an expression. That is sort of an inline case
statement. Using a dictionary it could be:

    result = condition from {True:expr1, False:expr0}

As a case using values as an index:

     case expr from [
        expr0,
        expr2,
        expr3 ]

Or using strings with a dictionary...

     case expr from {
        'a':expr0,
        'b':expr1,
        'c':expr3 }
     else:
        expr4

Reads nice, but can't put expressions in a dictionary or list without
them being evaluated first, and the [] and {} look like block brackets
which might raise a few complaints.

Can't help thinking of what if's. ;-)

Cheer's
Ron
Received on Thu Sep 29 16:40:24 2005