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.
bool([]) returns False as well. Usually, an empty list has a meaning that is different to None ; None means no value while an empty list means zero values. Semantically, they are different.
There's no null in Python; instead there's None . As stated already, the most accurate way to test that something has been given None as a value is to use the is identity operator, which tests that two variables refer to the same object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With