Python-list digest, Vol 1 #10572 - 14 msgs

Delaney, Timothy tdelaney at avaya.com
Mon Apr 22 20:32:41 EDT 2002


> From: Michael Gilfix [mailto:mgilfix at eecs.tufts.edu]
> 
>   void both_ways (int val, int direction)
>   {
>     another_func ( (direction) ? NULL : &val,
>                    (direction) ? &val : NULL,
>                     ....);
>   }

Urgh. Yuck. Ugly. I have *never* done this, in any language. I will always
compose the arguments correctly first, then call the function.

>   That way you can easily switch arguments to another function without
> more typing. But most people use the ternary operator as an if
> statement, which is ugly.

As is the above. The only use I have ever had for the ternary operator is of
the form:

    void both_ways (int val, int direction)
    {
        int *arg1 = direction ? NULL : &val;
        int *arg2 = direction ? &val : NULL;

        another_func(arg1, arg2, ...);
    }

Isn't that much cleaner and understandable than the above?

>   While I'm not commenting on whether this is really useful in python
> (because I get along fine without it), the python equiv would be:
> 
>   def both_ways (arg, dir):
> 
>     if dir:
>       arg1 = blah
>       arg2 = some_blah
>     else:
>       arg1 = something_else
>       arg2 = some_other_thing
> 
>     another_func (arg1, arg2)

I would rewrite this as:

def both_ways (val, direction):

    if dir:
        arg1, arg2 = None, val
    else:
        arg1, arg2 = val, None

    another_func(arg1, arg2, ...)

The thing is, the ternary operator is only more readable when dealing with a
single condition and single results. Adding even a single expression in
there starts making it unreadable. Any time things get more complicated, you
need to move to the if () {} else {} format anyway.

Tim Delaney





More information about the Python-list mailing list