For review: PEP 308 - If-then-else expression
Andrew Dalke
adalke at mindspring.com
Mon Feb 10 00:28:54 EST 2003
Paul Paterson
> As per a different thread where I did the reverse and searched the Python
> code in the Python standard library + assorted packages on my system.
One problem with this is that it doesn't capture the original author's
intent or practice. Some people like to have
if cond:
x = expr1
else:
x = expr2
either because of clarity or because it's easier to keep a
smaller set of language constructs in one's head or any of
the other reasons people have suggested here.
That's why I analyzed code from a language which already has
an if/else ternary expression. Eg, consider this example from Python's
C implementation, in cellobject.c (first one I found, but I imagine
there are plenty such examples)
if (b->ob_ref == NULL)
return 0;
return -1;
This could be written in C as
return b->ob_ref == NULL ? 1 : 0
but wasn't. Why wasn't it?
To repeat, just because the language supports a ?:-like expression
doesn't mean it's used. I believe it is used many fewer times
than it can be used.
> 769 candidates where the conditional expression could be used to replace
an
> assignment
> 381210 lines of code
>
> So as a rough estimate we get one use per (381210 - 4*769)/769 = 491
/lines
> of code.
>
> The actual usage is probably a lot more common that this as I only looked
> for the assignment pattern, but I would say the 1 in 200 lines is a fairly
> reasonable estimate.
That's a reasonable estimate of the number of times it COULD be
used. It isn't a reasonable estimate of the number of times it WILL
be used. I think it's much lower, closer to 1 in 1000 times or even
fewer.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list