On 2022-05-08 13:44, Chris Angelico wrote:
On Sun, 8 May 2022 at 22:09, Valentin Berlier <berlie...@gmail.com> wrote:

A while ago there was a discussion about allowing "match" patterns for the 
walrus operator. This would cover iterable unpacking as you suggested along with all the 
patterns allowed in match statements.

    if [x, y, z] := re.match(r"...").groups():
        print(x, y, z)

The walrus expression would evaluate to None if the pattern on the left can't 
be matched.


What if it does match, though? That's a little less clear. I like the
idea, but I'm not entirely sure what this should do, for instance:

print( {"x": x} := some_dict )

Clearly it should assign x to some_dict["x"] if possible, but then
what should get printed out? A small dict with one key/value pair? The
original dict? There would need to be a guarantee that the return
value is truthy, otherwise it'll create bizarre situations where you
try to match and it looks as if the match failed.

Perhaps the solution would be to add another operator, "?=", that would return True if the binding succeeded and False if it failed.

By the way: With any proposal to further generalize assignment
expressions, it'd be good to keep in mind the "implicit nonlocal"
effect that they currently have with comprehensions:

def f():
...     x, y = "old x", "old y"
...     print([(x := "new x") for y in ["new y"]])
...     return x, y
...
f()
['new x']
('new x', 'old y')


My best guess is that this effect should be extended to any simple
names that could _potentially_ be assigned to, even if (as in the case
of some match expressions) they might not all actually be assigned to.

_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/424EUXP35RIXQTJRCOZQCZPRHY7HT5F5/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to