1

Is there some conditional operator in Python which would evaluate the first operand and return its value if it's not None, or if it's None, evaluate and return the second operand? I know that a or b can almost do this, except that it does not strictly distinguish None and False. Looking for something similar to // operator in Perl.

The goal is to write both a and b only once, therefore alternative a if a is not None else b doesn't work either - both a and b can be expensive expressions.

Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43

2 Answers2

5

How about using the walrus operator?

tmp if (tmp := a()) is not None else b()

It will be faster than writing your own function, as function calls in Python incur a large overhead.

Hack5
  • 3,244
  • 17
  • 37
1

This works: a_ if (a_ := a) is not None else b - would this not account for a being only evaluated once?

Also see: What is the correct syntax for Walrus operator with ternary operator?