PEP 634: Reword sequence and mapping patterns sections to be more robust (#1937)

The new language is more precise, and leaves the door open for more implementation options, by not seeming to require that the pattern implementation must import collections.abc.

The new language allows only using sys.modules if has already been imported (e.g. by peeking in sys.modules).

Also, for internal use of CPython, two new flags, `Py_TPFLAGS_SEQUENCE` and `Py_TPFLAGS_MAPPING` are introduced, which support recognizing built-in sequence and mapping types without importing collections.abc.
This commit is contained in:
Mark Shannon 2021-04-26 15:10:51 +01:00 committed by GitHub
parent 0328f275c9
commit 6be779381a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 33 additions and 5 deletions

View File

@ -359,9 +359,29 @@ subpattern may occur in any position. If no star subpattern is
present, the sequence pattern is a fixed-length sequence pattern;
otherwise it is a variable-length sequence pattern.
A sequence pattern fails if the subject value is not an instance of
``collections.abc.Sequence``. It also fails if the subject value is
an instance of ``str``, ``bytes`` or ``bytearray``.
For a sequence pattern to succeed the subject must be a sequence,
where being a sequence is defined as its class being one of the following:
- a class that inherits from ``collections.abc.Sequence``
- a Python class that has been registered as a ``collections.abc.Sequence``
- a builtin class that has its ``Py_TPFLAGS_SEQUENCE`` bit set
- a class that inherits from any of the above.
The following standard library classes will have their ``Py_TPFLAGS_SEQUENCE``
bit set:
- ``array.array``
- ``collections.deque``
- ``list``
- ``memoryview``
- ``range``
- ``tuple``
Note::
Although, ``str``, ``bytes`` and ``bytearray`` are usually considered sequences,
they are not included in the above list and not considered to be sequences
when matching a sequence pattern.
A fixed-length sequence pattern fails if the length of the subject
sequence is not equal to the number of subpatterns.
@ -414,8 +434,16 @@ A mapping pattern may not contain duplicate key values.
syntax error; otherwise this is a runtime error and will
raise ``ValueError``.)
A mapping pattern fails if the subject value is not an instance of
``collections.abc.Mapping``.
For a mapping pattern to succeed the subject must be a mapping,
where being a mapping is defined as its class being one of the following:
- a class that inherits from ``collections.abc.Mapping``
- a Python class that has been registered as a ``collections.abc.Mapping``
- a builtin class that has its ``Py_TPFLAGS_MAPPING`` bit set
- a class that inherits from any of the above.
The standard library classes ``dict`` and ``mappingroxy`` will have their ``Py_TPFLAGS_MAPPING``
bit set.
A mapping pattern succeeds if every key given in the mapping pattern
is present in the subject mapping, and the pattern for