Defending the ternary operator
Andrew Dalke
adalke at mindspring.com
Mon Feb 10 02:04:03 EST 2003
Paul Paterson:
> Continuing the experiment to look at Python code which might use the
> conditional operator....
>
> If my regular expression is correct (and it probably isn't because I'm not
> good at them), then a quick scan of my Python22 directory structure finds
> 769 matches of the following pattern,
>
> if <something>
> variable = <some value>
> else:
> variable = <some other value>
>
> in 381209 lines of code. I leave the statistical interpretation to the
> reader.
You should also look at C/C++ code and see how many times C
code uses
if (something) {
variable = some_value;
} else {
variable = some_other_value;
}
For example, why doesn't this code from CPython's mmapmodule.c
use the ?: operator?
if (!map_size) {
m_obj->size = GetFileSize (fh, NULL);
} else {
m_obj->size = map_size;
}
After all, C has ?: so isn't this more readable, (insert pro-PEP arguments
here) as
m_obj->size = !map_size ? GetFileSize(fh, NULL) : map_size;
?
> I intend to post each one with an analysis of why they would or wouldn't
be
> better done using the new form....
Please also include the same analysis for Python's C implementation. ;)
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list