For review: PEP 308 - If-then-else expression

Paul Paterson hamonlypaulpaterson at houston.rr.com
Mon Feb 10 08:48:43 CET 2003


"Andrew Dalke" <adalke at mindspring.com> wrote in message
news:b27d3p$gm$1 at slb9.atl.mindspring.net...
> 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.

But if it did... now *that* would be a cool regular expression!

> 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.
>

No arguments from me - to the extent that one can draw anything from these
numbers 200, 500, 1000 are all pretty much the same. I suspect that we will
read and write them in this form a few times per module in the main. It's
possible that they might replace some instances of the initialization idiom,

def f(self, x=None):
    self.x = x if x or []   # explicit is better

in which case we would see more of them.






More information about the Python-list mailing list