[Info] PEP 308 accepted - new conditional expressions

  • Thread starter Reinhold Birkenfeld
  • Start date
C

Chris Smith

Duncan> The syntax is fine, but the semantics might not be what
Duncan> you expected. If I understand it correctly you need:

Duncan> return "the answer is " + ("yes" if X==0 else "no")

Duncan> Guido's pronouncement said:
I say, with the utmost arrogance, that I won't neglect the parens more
than, say, 50 times. ;)
-Chris
 
B

Bengt Richter

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.
But what you show doesn't require choice of which to _evaluate_,
since you are merely choosing between immutable constants, and there is
no side effect or computation overhead to avoid by not evaluating
the unselected expression. So

"the answer is " + ('no', 'yes')[X==0]

would do as well.
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"
As has been pointed out, though legal there is some doubt as to whether
you meant what you wrote ;-)
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

Regards,
Bengt Richter
 
A

Andrew Koenig

I think that part of the argument for the "A if C else B" syntax is that
"then" is not currently a reserved word.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top