13

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?

BhaveshDiwan
  • 669
  • 10
  • 22

2 Answers2

21

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.

chepner
  • 497,756
  • 71
  • 530
  • 681
11

For someone looking for a short answer or failing to grasp the accepted answer quickly like I did:

>>> variable = foo if (foo := 'parentheses!!') else 'otherwise'
>>> #                 ▲                      ▲
>>> #                 ╰──────────────────────╯
>>> variable
parentheses!!
Lars Blumberg
  • 19,326
  • 11
  • 90
  • 127