7

I just came across this idiom in some open-source Python, and I choked on my drink.

Rather than:

if isUp:
    return "Up"
else:
    return "Down"

or even:

return "Up" if isUp else "Down"

the code read:

return isUp and "Up" or "Down"

I can see this is the same result, but is this a typical idiom in Python? If so, is it some performance hack that runs fast? Or is it just a once-off that needs a code review?

Oddthinking
  • 24,359
  • 19
  • 83
  • 121

5 Answers5

17

The "a and b or c" idiom was the canonical way to express the ternary arithmetic if in Python, before PEP 308 was written and implemented. This idiom fails the "b" answer is false itself; to support the general case, you could write

 return (a and [b] or [c])[0]

An alternative way of spelling it was

 return (b,c)[not a]

which, with the introduction of the bool type, could be rewritten as

 return (c,b)[bool(a)]

(in case it isn't clear: the conversion to bool, and the not operator, is necessary if a is not known to be bool already)

Today, the conditional expression syntax should be used if the thing must be an expression; else I recommend to use the if statement.

Martin v. Löwis
  • 124,830
  • 17
  • 198
  • 235
  • 4
    The alternative syntax does have one difference to the and/or method or ternary operator - both values are always evaluated. Not a big deal if they are just variables, but if there are function calls (especially with side-effects) in there, it will make a difference. – Brian Dec 06 '08 at 11:00
9

You should read Using the and-or trick (section 4.6.1) of Dive Into Python by Mark Pilgrim. It turns out that the and-or trick has major pitfalls you should be aware of.

titaniumdecoy
  • 18,900
  • 17
  • 96
  • 133
0

That code is a big fugly and clever for my tastes, but I suppose there's not anything wrong with it per se. I think this is really just a case of "make it all fit in one line" syndrome.

I personally would have opted for the first form though.

Jason Baker
  • 192,085
  • 135
  • 376
  • 510
-1

No, it is not.

I had a somehow similar question the other day.

if the construct

val if cond else alt

Was not very welcome ( at least by the SO community ) and the preferred one was:

if cond:
    val
else:
    alt

You can get your own conclusion. :)

Community
  • 1
  • 1
OscarRyz
  • 196,001
  • 113
  • 385
  • 569
-1

Yikes. Not readable at all. For me pythonic means easy to read.

return isUp and "Up" or "Down"

Sounds something you would do in perl.

Kozyarchuk
  • 21,049
  • 14
  • 40
  • 46