Petr
Petr

Reputation: 63389

How to supply a default value iff a value is None?

Is there an operator or a library function such that v ??? d

(where by ??? I denote the operator I'm seeking).

Operator or is almost what I want, but it evaluates to the default value if v is False. I want the default only if the argument is None, so that False ??? d evaluates to False.


Update: To clarify, in my case v can be a complex expression, like computeSomethingLong() ??? d. So I can't use

computeSomethingLong() if computeSomethingLong() is not None else d

I'd have to do something like

tempvar = computeSomethingLong()
tempvar if tempvar is not None else d

which feels quite awkward, compared to computeSomethingLong() or d.


Update: The closest I got is to define my own function:

def orElse(v, deflt):
    if v is not None:
        v
    else:
        deflt

But the drawback is that deflt is always evaluated! I want it to evaluate only if it's actually needed. In particular, I want that in

firstLongComputation() ??? secondLongComputation()

the first computation is evaluated; if it's result is not None, it is returned. Otherwise the second one is evalauted (and only in this case) and it will be the result of the expression.

Upvotes: 1

Views: 188

Answers (2)

J0HN
J0HN

Reputation: 26951

There's no such operator, but it's straigtforward anyway using ternary if "operator"

v if v is not None else d

If v is an expensive function call, you can employ any kind of caching (aka memoization) to still use the same approach:

@memoize
def computeSomethingLong():
   """whatever"""

computeSomethingLong() if computeSomethingLong() else computeSomethingElse()

Will still evaluate computeSomethingLong once.

See python manual or some other instructions for details on decorators.

Upvotes: 5

Alvaro
Alvaro

Reputation: 2327

Try with v if v is not None else d

Upvotes: 0

Related Questions