> 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.
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.
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/YQRKWVCEAQ7D67ODF74IVBDLVXAQGQOL/
Code of Conduct: http://python.org/psf/codeofconduct/