substitute for c/java's ?:

Jochen Riekhof jochen at riekhof.de
Thu Jun 14 07:59:53 EDT 2001


> Trust me, this is true.
Nope.

haha, the usual examples that shall prove how great one's favorite language
is. During the many years of programming I finally
managed to drop the evangelism (am, well... almost ;-). I can encourage
everyone to do the like, as one lives more comfortable and has a greater
chance to be unbiased.
The longish java code can e.g. be rewritten as

/**Utility which returns 'a' or 'an' for a given noun. */
public static final String aan(String name) {
    return ("aeiou".indexOf(name.toLowerCase().charAt(0))  < 0) ? "a" :
"an";
}

which, compared to

def aan(name):
    """Utility which returns 'a' or 'an' for a given noun.
    """
    if string.lower(name[0]) in ('a','e','i','o','u'):
        return 'an '
    else:
        return 'a '

is not all that bad ;-). Of course you can use if else you like this better.
In particular this is not my favourite use of ?:, I would probably have used
if/else as well here..

But there is often the need to assign one of two values depending on a
simple condition.
if a == 0:  result = value1
else:         result = value2

This is more readable and faster to understand (just  because there is less
code) with ?:.
result = (a == 0) ? value1 : value2;

This is especially important when result is a more longish expression.

With only moderate experience the meaning is clear at a glance. For this
cases I miss ?:. Just my opinion ;-)

What do you think?

Neil and Remco wrote:

>cases = {"dog": Dog, "cat": Cat, "rabbit": Rabbit}
>
> def createPet(type="cat"):
>     if casses.has_key(type): return casses[type]() #Good input...
>     else: return None   # bad input, or 'default' in C/java

Nice trick!

>result = option and value1 or value2


also nice, almost forgot about this feature (result is last evaluated code)!

Thanks!

Ciao

...Jochen










More information about the Python-list mailing list