Author quentel
Recipients quentel
Date 2021-07-09.10:16:54
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1625825814.86.0.0898667876443.issue44589@roundup.psfhosted.org>
In-reply-to
Content
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}:
History
Date User Action Args
2021-07-09 10:16:54quentelsetrecipients: + quentel
2021-07-09 10:16:54quentelsetmessageid: <1625825814.86.0.0898667876443.issue44589@roundup.psfhosted.org>
2021-07-09 10:16:54quentellinkissue44589 messages
2021-07-09 10:16:54quentelcreate