Is there a way to do an assignment only if the assigned value is not None, and otherwise do nothing?
Of course we can do:
x = get_value() if get_value() is not None
but this will read the value twice. We can cache it to a local variable:
v = get_value()
x = v if v is not None
but now we have made two statements for a simple thing.
We could write a function:
def return_if_not_none(v, default):
if v is not None:
return v
else:
return default
And then do x = return_if_not_none(get_value(), x)
. But surely there is already a Python idiom to accomplish this, without accessing x
or get_value()
twice and without creating variables?
Put in another way, let's say =??
is a Python operator similar to the C# null coalesce operator. Unlike the C# ??=
, our fictional operator checks if the right hand side is None
:
x = 1
y = 2
z = None
x =?? y
print(x) # Prints "2"
x =?? z
print(x) # Still prints "2"
Such a =??
operator would do exactly what my question is asking.
In python 3.8 you can do something like this
if (v := get_value()) is not None:
x = v
Updated based on Ryan Haining solution, see in comments