Defending the ternary operator

Paul Rubin phr-n2003b at NOSPAMnightsong.com
Sat Feb 8 19:50:15 EST 2003


"Andrew Dalke" <adalke at mindspring.com> writes:
> EXAMPLE 1: (used 6 times)
> 
>   return arr[i] & mask ? true : false;
> 
> (This C++ code was pre any sort of built-in boolean so
> those two values are defined as part of their package, I think.)
> 
> Python now has a bool, so this could be written as
>    return bool(arr[i] & mask)
> 
> If C++ does have a boolean type, then this isn't needed.  Even
> when it didn't exist, it would have been easy to define, just like
> the values 'true' and 'false' were defined.

It's still needed, if you want the function to return true or
false, instead of considering 0x1 and 0x04000 to be equivalent.

> EXAMPLE 2:
> 
> ClassSpam::ClassSpam(huge, set, of, args, including, input_arg)
>  : instance_var(input_arg ? 2 : 1)
> {
>   ... rest of constructor ...
> }
> 
> One way to do this in Python (besides an if/then statement) is
>    self.instance_var = bool(input_arg) + 1
> 
> This is needed for C++ because it's the only way to initialize
> const values.  It isn't needed in Python.

I don't understand this one so I'll skip it.

> EXAMPLE 3: (used twice, 3x each)
> 
>   sprintf(outputStr, msgFmt, is_clean ? "CLEAN": "DIRTY",
>             "spam=", spamStr,
>             output_format == FORMAT1 ? "STR1" : "STR2",
>             output_format == FORMAT1 ? "" : output_filename
> 
> consider instead
> 
>    if self.output_format == FORMAT1:
>      output_info = ("STR1", "")
>   else:
>     output_info == ("STR2", output_filename)
>    print >> outputStr, msgFmt % ((["DIRTY", "CLEAN"][self.is_clean],
>           "spam=", self.spamStr) + output_info)
> 
> For C++ this is useful.  Doesn't mean it's needed for Python.

Doing it the same way in Python looks ok to me.

> EXAMPLE 4:
> 
> Personally, I can't figure out what this code is doing.  Not because
> of the ?:, which looks like
> 
>   if (!ExportAs(inputStr, usingChemDraw ? CHEMDRAW : outputFilename))
> 
> but because the surrounding code is complicated.

In that case the ?: isn't the issue.
> 
> EXAMPLE 5:
> 
>   // flg can be 0 ("no"), 1 ("same as last time"), or 2 ("yes")
>   if (flg != 1 && cursor && (cursor.dirty() ? !flg : flg) {
>      delete cursor;
>      cursor = NULL;
>   }
>   if (!cursor) ...
> 
> 
> I have a hard time following the logic.  I think it's more
> understandable as
> 
>   if ((flg == 0 and cursor and cursor.dirty()) or
>       (flg == 2 and cursor and not cursor.dirty()):
> 
> assuming I didn't get something swapped.

Yes, it's clearer as originally written, no problem with getting
something swapped.

And so on for other examples...




More information about the Python-list mailing list