With the introduction of PEP-622, we have the elegant and succinct syntax of matching a value by an instance of a class while also assigning attribute values of the instance to variables, e.g.:
class Point:
x: int
y: int
p = Point(0, 1)
match p:
case Point(x=0, y=y):
print(f"Y={y} and the point is on the y-axis.")
Would it not be nice if we can have such a match-capture-and-assign mechansim in regular assignments as well? Think of it as more generalized unpacking.
Instead of:
assert isinstance(p, Point)
x = p.x
y = p.y
we can have:
Point(x, y) = p
or by keyword:
Point(x=x, y=y) = p
Instead of:
assert isinstance(p, Point) and p.x == 0
y = p.y
we can have:
Point(0, y) = p
Instead of:
assert isinstance(p, Point)
y = p.y
we can have:
Point(_, y) = p
Mapping patterns can be supported too, and like structural pattern matching, extra keys can be ignored.
Instead of:
p = {'x': 0, 'y': 1, 'z': 0}
x = p['x']
y = p['y']
we can have:
p = {'x': 0, 'y': 1, 'z': 0}
{'x': x, 'y': y} = p
Unlike a match-case
construct, we always have only one matching pattern on the left in an assignment, so would it not be nice if we can also perform type conversions during a match?
Instead of:
for name, x, y in csv.reader(['top,0,1', 'right,1,0', 'top-right,1,1']):
x = float(x)
y = float(y)
print(f'distance to {name} is {(x * x + y * y) ** .5}')
we can have:
for name, float(x), float(y) in csv.reader(['top,0,1', 'right,1,0', 'top-right,1,1']):
print(f'distance to {name} is {(x * x + y * y) ** .5}')
Unlike structural pattern matching, an assignment with just classes or literals but no variables on the left should not be allowed:
Point(0, 1) = p # error
{'x': 0, 'y': 1} = p # error