PEP 308: A PEP Writer's Experience - PRO

Tim Peters tim.one at comcast.net
Sun Feb 9 13:24:19 EST 2003


[Andrew Koenig]
> Here's a different example that you may find more persuasive.
>
> Recall that many programs take file names as parameters, and some of
> those use the convention that if the file name is "-", the program
> should process the standard input instead of opening a file.
>
> Suppose we want to print the identity of the file that we are about to
> process.  In other words, we want to print "Processing", followed by
> either "<stdin>" or the file name, depending on whether the
> file name is "-".
>
> Then I would like to be able to write this:
>
>     print "Processing", "<stdin>" if filename == "-" else filename

The problem with the example is that it's already easily expressed safely by
the and/or idiom,

    print "Processing", filename == "-" and "<stdin>" or filename

There are at least 100 uses akin to this in Python's standard library today:

print "auto colorizing turned", self.allow_colorizing and "on" or "off"
cfile = fullname + (__debug__ and 'c' or 'o')
log.info(ok and "success!" or "failure.")
... isfirstline() and "*" or "" ...
__builtin__.__dict__['_'] = unicode and self.ugettext or self.gettext
_suffix_char = __debug__ and 'c' or 'o'
iptfile = args and args[0] or "Python/graminit.c"
mname = p.__name__ and p.__name__+'.'+name or name
self.write(obj and TRUE or FALSE)
pos is None and "<unknown>" or pos,
contents = doc and [doc + '\n'] or []
line = (name and self.bold(name) + ' = ' or '') + repr
host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost'
font = ('helvetica', sys.platform == 'win32' and 8 or 10)
write(value and "1" or "0")

and many more.  The short-circuiting business is supplied by that idiom but
is rarely needed (for example, it's not needed in any of the above), and
it's usually certain that the thing following "and" can't be false (its only
insecurity -- nothing in the std library needs to worry about that case).

> ...
> Of course, I don't consider this argument to be proof.  There isn't
> going to be any proof in this discussion, because the whole question
> is *always* about which of two equivalent forms to prefer.

I like the existing uses of and/or fine, and prefer them to multiline
spellings given what simple cases they are.  Well, almost all.  I don't care
for this line from imaplib.py -- but I wouldn't like it any better under the
PEP's spelling either:

l = map(lambda x:'%s: "%s"' % (x[0], x[1][0] and '" "'.join(x[1]) or ''), l)






More information about the Python-list mailing list