I read in Twitter:
#Python news: Guido accepted PEP 572. Python now has assignment expressions.
if (match := (pattern.search) pattern.search(data)) is not None: print((match.group) mo.group(1)) filtered_data = [y for x in data if (y := f(x)) is not None]
(correction mine in the 2nd line of code)
As indicated, PEP 572 -- Assignment Expressions describes this to be present in Python 3.8:
This is a proposal for creating a way to assign to variables within an expression using the notation
NAME := expr
.
I've gone through the description and examples and I see this is a convenient way to avoid repetitions of either calls or assignments, so instead of:
match1 = pattern1.match(data)
match2 = pattern2.match(data)
if match1:
return match1.group(1)
elif match2:
return match2.group(2)
or the more efficient:
match1 = pattern1.match(data)
if match1:
return match1.group(1)
else:
match2 = pattern2.match(data)
if match2:
return match2.group(2)
One now can say:
if match1 := pattern1.match(data):
return match1.group(1)
elif match2 := pattern2.match(data):
return match2.group(2)
Similarly, one can now say:
if any(len(longline := line) >= 100 for line in lines):
print("Extremely long line:", longline)
However, I do not understand how this example given in the PEP is not valid:
y0 = y1 := f(x) # INVALID
Will it be correct to say y0 = (y1 := f(x))
? How could it be used?
Foot note for those who wonder where will this be available: I already installed Python 3.7 and it does not work there, since the PEP currently shows as "Status: Draft". However, the PEP talks about Proof of concept / reference implementation (https://github.com/Rosuav/cpython/tree/assignment-expressions), so it is a matter of using their Python 3.8 alpha 0 version that includes it.
As explicitly stated in the PEP,
And later,