1
def test(x):
  print("in test")
  if x >0:
    return 1
  else:
    None
def whennegative():
  return 6
myval =test(3) if test(3) else whennegative()

Is there anyway do this one-line if-else without execute test twice? thanks

Kang
  • 47
  • 1
  • 4

1 Answers1

2

What you're writing can be summarized as "Do test(3) if it works, and if it doesn't, then here's a fallback". Put another way, that can be summarized as "Do test(3), or else do the fallback".

myval = test(3) or whennegative()

If test(3) is truthy, it'll short circuit out. Otherwise, it'll evaluate whennegative().

There are people who will argue that this is too short and clever, and it can certainly be overused (if you ever see a = (b and c) or d then you've gone too far). But a single or in assignment to mean "here's a fallback" or a single and to mean "here's a point of failure" is pretty well understood by folks and is, indeed, more concise than the ternary alternative.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116