On 2020-10-23 23:25, Valentin Berlier wrote:
Pattern-matching is great. I think PEP 634 is on the right track, but it would be a waste to only use pattern-matching for choosing a branch in a match statement.
Let’s look at Rust:
if let [x, y] = my_array { ... }
Rust "if let" constructs are an alternative to full-blown match statements that make it less verbose to match a single pattern.
We have a similar problem. The syntax proposed by PEP 634 is pretty verbose for matching a single pattern:
match my_list: case [x, y]: ...
Two keywords and two indentation levels. We can do better:
if [x, y] := my_list: ...
Yes, your first intuition is right. This looks similar to the Rust version but would work completely differently. But hear me out. Let's look past my terrible example and focus on the idea.
1. The walrus operator was purposefully designed to create bindings and not to perform assignments to arbitrary lvalues. 2. Matching a pattern only introduces bindings as well, no assignments. 3. The current behavior of the walrus operator is equivalent to matching the right-side operand to an "irrefutable" capture pattern.
Allowing the walrus operator to do pattern-matching would simply make the returned value conditional. If the pattern doesn't match, the walrus operator returns None.
print(x := 42) # 42 print(1 := 42) # None
Why should a failed match return None? That's not helpful if it matches but the value itself is None. [snip]