On Mon, 9 May 2022 at 00:04, Valentin Berlier <berlie...@gmail.com> wrote:
>
> > What if it does match, though?
>
> The walrus operator returns the value on the right side so this wouldn't 
> change. In your example the original dict would get printed.
>
> some_dict  = {"x": 1, "y": 2}
> print({"x": x} := some_dict)  # {"x": 1, "y": 2}
>
> The only pattern where it's not possible to know if the pattern was matched 
> by looking at the return value is the None pattern:
>
> print(None := x)
>
> If the pattern matches this will print the value of x, None, and if the 
> pattern doesn't match this will also print None because the walrus operator 
> evaluates to None instead of the value on the right side when the pattern 
> doesn't match. This is not a problem since testing for None is normally done 
> with the is operator: x is None
>
>
> The only patterns where it's not possible to know if the pattern was matched 
> by looking at the truthiness of the return values are the following:
>
> print(None := x)
> print(False := x)
> print(0 := x)
> print(0.0 := x)
> print("" := x)
> print([] := x)
> print({} := x)
>
> This is not a problem since in all of these cases testing for truthiness is 
> normally done with bool() or by testing the value directly in an if statement.

Yes, but what if you're testing for something that could *potentially*
match one of these empty objects? There's a reason that re.match
always returns a match object, NOT the matched string, because if a
regex matches an empty string, "if re.match(...)" should still count
it as true.

> In my opinion the behavior is fairly unsurprising: return the right side if 
> the pattern matches or None otherwise. We can even explain the current 
> restricted behavior in terms of pattern matching: the name on the left side 
> is an "irrefutable" pattern which will always match and therefore always 
> return the right side of the expression.
>

There will always be edge cases, though. Maybe pathological ones, but
edge cases nonetheless. I'm worried that this will end up being a bug
magnet, or conversely, that people will have to work around it with
"if ([x] := foo()) is not None:", which is way too clunky.

But I would like to see something like this happen. A match expression
is also something people have wanted from time to time.

ChrisA
_______________________________________________
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/LHY4XODZNZOGMJXVRCDTGIT765BRMJL5/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to