3

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.

fedorqui 'SO stop harming'
  • 228,878
  • 81
  • 465
  • 523

1 Answers1

5

As explicitly stated in the PEP,

Unparenthesized assignment expressions are prohibited at the top level in the right hand side of an assignment statement; for example, the following is not allowed:

y0 = y1 := f(x)  # INVALID

Again, this rule is included to avoid two visually similar ways of saying the same thing.

And later,

As follows from section "Exceptional cases" above, it is never allowed at the same level as =. In case a different grouping is desired, parentheses should be used.

...

# INVALID
x = y := 0

# Valid alternative
x = (y := 0)
Community
  • 1
  • 1
user2357112 supports Monica
  • 215,440
  • 22
  • 321
  • 400