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.

3
  • You can write a function to do this. Commented Jun 16, 2023 at 19:13
  • 1
    PEP 505 proposes such an operator (a ?? b), but it's suspended in limbo.
    – chepner
    Commented Jun 16, 2023 at 19:19
  • Your title says "defined", your text says "not None. Which one is it? Commented Jun 16, 2023 at 19:19

2 Answers 2

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.

2
  • 1
    Elvis is ?:, := is walrus.
    – Czaporka
    Commented Jun 16, 2023 at 19:22
  • 2
    Oops :/ it's been a long day
    – Hack5
    Commented Jun 16, 2023 at 19:23
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?

1
  • 2
    Pretty sure that's invalid, since order of operations will make that (a_ := (a is not None)). I think that should be (a_ := a) is not None Commented Jun 16, 2023 at 19:21

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.