To assign the result of a function
get_value() to variable
x if it is different from
None, use the Walrus operator
if tmp := get_value(): x = tmp within a single-line if block. The Walrus operator assigns the function’s return value to the variable
tmp and returns it at the same time, so that you can check and assign it to variable
x subsequently.
Problem: How to assign a value to a variable if it is not equal to
None—using only a single line of Python code?
Example: Say, you want to assign the return value of a function get_value(), but only if it doesn’t return None. Otherwise, you want to leave the value as it is. Here’s a code example:
import random def get_value(): if random.random()>0.5: return None return 1 # Naive approach: x = 42 tmp = get_value() if tmp != None: x = tmp print(tmp)
While this works, you need to execute the function
get_value() twice which is not optimal. An alternative would be to assign the result of the
get_value() function to a temporary variable to avoid repeated function execution:
x = 42 temp = get_value() if temp != None: x = temp print(x)
However, this seems clunky and ineffective. Is there a better way?
Let’s have an overview of the one-liners that conditionally assign a value to a given variable:
Exercise: Run the code. Does it always generate the same result?
Method 1: Ternary Operator + Semicolon
The most basic ternary operator
x if c else y consists of three operands
x,
c, and
y. It is an expression with a return value. The ternary operator returns
x if the Boolean expression
c evaluates to
True. Otherwise, if the expression
c evaluates to
False, the ternary operator returns the alternative
y.
You can use the ternary operator to solve this problem in combination with the semicolon to write multiple lines of code as a Python one-liner.
# Method 1 tmp = get_value(); x = tmp if tmp else x
You cannot run the
get_value() function twice—to check whether it returns
True and to assign the return value to the variable
x. Why? Because it’s nondeterministic and may return different values for different executions.
Therefore, the following code would be a blunt mistake:
x = get_value() if get_value() else x
The variable
x may still be
None—even after the ternary operator has seemingly checked the condition.
Related articles:
Method 2: Walrus + One-Line-If
A beautiful extension of Python 3.8 is the Walrus operator. The Walrus operator
:= is an assignment operator with return value. Thus, it allows you to check a condition and assign a value at the same time:
# Method 2 if tmp := get_value(): x = tmp
This is a very clean, readable, and Pythonic way. Also, you don’t have the redundant identity assignment in case the if condition is not fulfilled.
Related Article: The Walrus Operator in Python 3.8!!