PEP 308: A PEP Writer's Experience - PRO
Tim Peters
tim.one at comcast.net
Sat Feb 8 12:36:32 EST 2003
[Michael Chermside]
> If a ternary expression is available, then things can be done in
> expressions which would be impossible without it. lambda is the
> example most often given, but I think a different example is
> more compelling. Suppose you want to write a line of logging
> into your program:
>
> print "x = " + x.getDisplayString()
>
> but you have to allow for the fact that x might be None. With
> a ternary expression, you can write this:
>
> print "x = " + x.getDisplayString() if x else "None"
[Aahz]
> Why not
>
> print 'x =', x.getDisplayString()
>
> or
>
> print 'x = ' + str(x.getDisplayString())
Presumably because, if x is None, None.getDisplayString() will blow up.
> The point is that many of the supposed uses for ternary do have simple,
> effective workarounds.
This isn't one of 'em <wink>.
OTOH, when I read Micahel's post, I had no idea whether
print "x = " + x.getDisplayString() if x else "None"
would group as:
print ("x = " + (x.getDisplayString() if x else "None"))
or as:
print (("x = " + x.getDisplayString()) if x else "None")
and I didn't even know which way he *intended*. Spelled with an if-
statement instead, the intent is obvious instead of a puzzle.
More information about the Python-list
mailing list