New submission from Pierre Quentel <pierre.quen...@gmail.com>:
PEP 634 specifies that "A mapping pattern may not contain duplicate key values. (If all key patterns are literal patterns this is considered a syntax error; otherwise this is a runtime error and will raise ValueError.)" but this is not what happens with the latest release: Python 3.10.0b3 (tags/v3.10.0b3:865714a, Jun 17 2021, 20:39:25) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> x = {'a': 1} >>> match x: ... case {'a': 1, 'a': 2}: # (A) ... print('ok') ... >>> x = {'a': 3} >>> match x: ... case {'a': 1, 'a': 2}: # (B) ... print('ok') ... >>> x = {'a': 1, 'b': 2} >>> match x: ... case {'a': 1, 'a': 2}: # (C) ... print('ok') ... Traceback (most recent call last): File "<stdin>", line 2, in <module> ValueError: mapping pattern checks duplicate key ('a') >>> If I understand the PEP correctly, all these examples should raise a SyntaxError for the line case {'a': 1, 'a': 2}: since all key patterns are literal patterns, and the key 'a' is duplicated. Cases (A) where the subject matches one of the key-value patterns, and (B) when it doesn't, fail without raising SyntaxError. Case (C) where one of the keys in the subject is not present in the mapping pattern raises a ValueError at runtime instead of SyntaxError. This behaviour is tested in test_patma.py: def test_patma_251(self): x = {"a": 0, "b": 1} w = y = z = None with self.assertRaises(ValueError): match x: case {"a": y, "a": z}: w = 0 self.assertIs(w, None) self.assertIs(y, None) self.assertIs(z, None) but this doesn't seem compliant with the specification. BTW, it's not clear to me why the SyntaxError should be limited to the case when all keys are literal patterns; it could be raised whenever a literal pattern is repeated, even when there are value patterns or a double-star pattern, like in case {'a': 1, 'a': 2, c.imag, **rest}: ---------- components: Interpreter Core messages: 397195 nosy: quentel priority: normal severity: normal status: open title: Pattern Matching - duplicate keys in mapping patterns versions: Python 3.10 _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue44589> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com