It is not syntactic sugar, "x := 10" is an assignment expression in contrast with "x = 10", which is a statement.
Hence the former can be used in contexts like "if x := 10: pass", which is the whole point of the PEP.
replies(2):
Hence the former can be used in contexts like "if x := 10: pass", which is the whole point of the PEP.
I'd prefer more lines for readability reasons.
if (match := re.match(r1, s)):
o = match.group(1)
elif (match := re.match(r2, s)):
o = match.group(1)
match = re.match(r1, s)
if match:
o = match.group(1)
else:
match = re.match(r2, s)
if match:
o = match.group(1)
or a bit shorter: match = re.match(r1, s)
if not match:
match = re.match(r2, s)
if match:
o = match.group(1)
You could also just loop: for pattern in (r1, r2, ...):
match = re.match(pattern, s)
if match:
o = match.group(1)
break
else:
do_failure_handling()
But this goes a bit beyond the original question. if (match := re.match(r1, s)):
o = match.group(1)
# plus some code here
elif (match := re.match(r2, s)):
o = match.group(2)
# plus some other code here
In this case only your first solution works, I think. Leaving aside that having those deeply nested ifs is incredibly ugly, I find it hard to accept that something which completely changes the possible structure of the code is just "syntactic sugar".But the overall question is: when is the sugar just syntactical, and at what point does it become a complete new taste?