1

Just a small question about ternary conditional operator which has confused me for a long time.

Code for example (python 2.7):

>>> x, y = None, 3
>>> x, y
(None, 3)
>>> (x == None and x or y)
3
>>> (x != None and x or y)
3
>>> (x if x == None else y)

The third and forth lines are old-style conditional operator. Both give the same result. And obviously, the former takes "wrong" result. Maybe it's not wrong according to python. But it's very easy to make the mistake in program and without explicit error.

The fifth line are new-style from version 2.5 according to the book "Core python programming" (Wesley J. Chun) and its return is right.

Does someone know something about this?

3
  • whats the question? ... the "new" version is more verbose (explicit is better than implicit) Commented May 20, 2013 at 5:13
  • Only the last one is the ternary operator, which is perhaps why it works? Commented May 20, 2013 at 5:17
  • 3
    @JoranBeasley, and most importantly, correct. Unlike the old version. Commented May 20, 2013 at 5:17

3 Answers 3

5

Your third and fourth lines aren't a ternary operator. They're an attempt to hack a ternary operator using other operators, but, as you saw, they don't really work, because the logical operators you're using depend on the notion of "boolean falseness", not just of the condition, but of the results you want to return based on the condition. The real ternary operator was added precisely so you don't have to use that sort of fakery anymore.

Sign up to request clarification or add additional context in comments.

Comments

2

This is a known problem with this "conditional operator" hack. it does not work.

x == None => true. Continue to the "and" part, as expected.

and x => false (since x is None, and None is false). the whole and expression evaluates to false, hence or y comes into play. result is y.

1 Comment

Yes, I got it. Thanks for your logical analysis.
1

It's not wrong. It's just the way that truthy and falsy values work.

(x != None and x or y) is evaluated like ((x != None) and x) or y, which will return y in both cases if x is falsy. False and False and True and False are both False, so the short-circuiting or will return y.

The and ... or trick isn't actually a ternary operator, as there's no condition. It's just relying on the fact that or short-circuits, so if x != None and x is truthy, y won't be evaluated. The new-style is an actual ternary operator.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.