Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One liner to "assign if not None"

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.

like image 230
Donentolon Avatar asked Jan 17 '20 01:01

Donentolon


People also ask

What is the opposite of none in Python?

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.

IS NULL operator in Python?

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.


1 Answers

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

like image 105
alex2007v Avatar answered Nov 02 '22 23:11

alex2007v