'What is the correct syntax for Walrus operator with ternary operator?

Looking at Python-Dev and StackOverflow, Python's ternary operator equivalent is:

a if condition else b

Looking at PEP-572 and StackOverflow, I understand what Walrus operator is:

:=

Now I'm trying to to combine the "walrus operator's assignment" and "ternary operator's conditional check" into a single statement, something like:

other_func(a) if (a := some_func(some_input)) else b

For example, please consider the below snippet:

do_something(list_of_roles) if list_of_roles := get_role_list(username) else "Role list is [] empty"

I'm failing to wrap my mind around the syntax. Having tried various combinations, every time the interpreter throws SyntaxError: invalid syntax. My python version is 3.8.3.

My question is What is the correct syntax to embed walrus operator within ternary operator?



Solution 1:[1]

Syntactically, you are just missing a pair of parenthesis.

do_something(list_of_roles) if (list_of_roles := get_role_list(username)) else "Role list is [] empty"

If you look at the grammar, := is defined as part of a high-level namedexpr_test construct:

namedexpr_test: test [':=' test]

while a conditional expression is a kind of test:

test: or_test ['if' or_test 'else' test] | lambdef

This means that := cannot be used in a conditional expression unless it occurs inside a nested expression.

Solution 2:[2]

For someone looking for a short answer, as most programmers run fast, or just fail to grasp the accepted answer quickly like I did:

>>> variable = foo if (foo := 'put parentheses here!') else 'otherwise'
>>> variable
put parentheses here!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Lars Blumberg