PEP 308: A PEP Writer's Experience - PRO

Tim Peters at
Mon Feb 10 05:26:42 CET 2003

> Tim> The problem with the example is that it's already easily
> Tim> expressed safely by the and/or idiom,
> Tim>     print "Processing", filename == "-" and "<stdin>" or filename

[Andrew Koenig]
> But it's safe only by coincidence.  In particular, if you change
> "<stdin>" to "", it breaks.

I used to buy that, but I'm having a harder time now.  I mean the "by
coincidence" part, not the "if ... it breaks" part.  As I said, there are
over 100 uses of and/or in the standard library now, all I looked at were
obviously safe at a glance, and I have yet to find real code in the library
where something stronger than and/or would actually help.

> To me, the apparently widespread use of an idiom that works only
> because the middle value happens to be nonempty is strong evidence
> that we should have a more robust and universal way of expressing
> this particular idea.

The rub is that it's overwhelmingly the case that "the middle value" is a
literal or global CONSTANT with an obviously true value.  It's not the case
that a string like "yes" just happens to be nonempty -- it can't be empty
and still say "yes" <wink>.  I don't think it's coincidence either that the
usual outcome gets put in "the middle position" (the first of the two
possible positions for it), or that the usual outcome is a non-trivial one.

It's a fact that worry about "the empty case" is worry about a bug I've
never seen in real life (and recalling that Python does have min(), max()
and abs() builtin -- I'd never use and/or for them).  I invented the

    (cond and (x,) or (y,))[0]

"idiom" in the early 90's in a thread where Steven Majewski and I were idly
wondering whether it was possible to emulate cond?x:y exactly in a short
one-liner.  I've never used it, and it occurs to me it's not because it's
too ugly to bear (although it is), but because and/or is the strongest thing
I ever actually needed.

More information about the Python-list mailing list