Reputation: 63389
Is there an operator or a library function such that v ??? d
v
if v
is distinct from None
and doesn't evaluate d
, ord
if v
is equal to None
.(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
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