[Info] PEP 308 accepted - new conditional expressions

Chris Smith smitty_one_each at bigfoot.com
Wed Oct 12 02:15:40 EDT 2005


>>>>> "Sebastian" == Sebastian Bassi <sbassi at gmail.com> writes:

    Sebastian> On 9/30/05, Reinhold Birkenfeld <reinhold-birkenfeld-nospam at wolke7.net> wrote:
    >> after Guido's pronouncement yesterday, in one of the next
    >> versions of Python there will be a conditional expression with
    >> the following syntax: X if C else Y

    Sebastian> I don't understand why there is a new expression, if
    Sebastian> this could be accomplished with:

    Sebastian> if C: X else: Y

    Sebastian> What is the advantage with the new expression?

One very frequent use case is building a string.
Instead of:

if X==0:
   filler="yes"
else:
   filler="no"
return "the answer is %s" % filler


What I really want to do is take four lines of conditional, and put
them into one, as well as blow off dealing with a 'filler' variable:

return "the answer is " + "yes" if X==0 else "no"


Or whatever the final release syntax is.
Conditional expressions are a nice way to shim something in place, on
an acute basis.  Chronic use of them could lead to a full-on plate of
spaghetti, where you really wanted code.
They can be impenitrable.  Whenever I'm dealing with them in C/C++, I
always line the ?, the :, and the ; characters vertically, which may
seem a bit excessive in terms of whitespace, but provides a nice
hieroglyph over on the right side of the screen, to make things
obvious.
Best,
Chris



More information about the Python-list mailing list