PEP 622: Rename 'named sub-pattern' to 'walrus pattern' (#1482)

This commit is contained in:
Guido van Rossum 2020-06-30 20:26:10 -07:00 committed by GitHub
parent f9ba5a955c
commit 2e8df86101
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 11 additions and 11 deletions

View File

@ -139,7 +139,8 @@ A simplified, approximate grammar for the proposed syntax is::
match_stmt: "match" expression ':' NEWLINE INDENT case_block+ DEDENT
case_block: "case" pattern [guard] ':' block
guard: 'if' expression
pattern: NAME ':=' or_pattern | or_pattern
pattern: walrus_pattern | or_pattern
walrus_pattern: NAME ':=' or_pattern
or_pattern: closed_pattern ('|' closed_pattern)*
closed_pattern:
| literal_pattern
@ -507,22 +508,20 @@ is a ``SyntaxError`` and ``1 | 2 if 3 | 4`` will be parsed as
``(1 | 2) if (3 | 4)``.
.. _named:
Walrus patterns
---------------
Named sub-patterns
------------------
It is often useful to match a sub-pattern *and* to bind the corresponding
It is often useful to match a sub-pattern *and* bind the corresponding
value to a name. For example, it can be useful to write more efficient
matches, or simply to avoid repetition. To simplify such cases, a capture pattern
can be combined with another arbitrary pattern using named sub-patterns of
the form ``name := pattern``. For example::
matches, or simply to avoid repetition. To simplify such cases, any pattern
(other than the walrus pattern itself) can be preceded by a name and
the walrus operator (``:=``). For example::
match get_shape():
case Line(start := Point(x, y), end) if start == end:
print(f"Zero length line at {x}, {y}")
Note that the capture pattern used in the named sub-pattern can be used in
The name on the left of the walrus operator can be used in a guard, in
the match suite, or after the match statement. However, the name will
*only* be bound if the sub-pattern succeeds. Another example::
@ -1728,7 +1727,8 @@ Other notation used beyond standard EBNF:
case_block: "case" patterns [guard] ':' block
guard: 'if' named_expression
patterns: value_pattern ',' [values_pattern] | pattern
pattern: NAME ':=' or_pattern | or_pattern
pattern: walrus_pattern | or_pattern
walrus_pattern: NAME ':=' or_pattern
or_pattern: '|'.closed_pattern+
closed_pattern:
| capture_pattern