PEP 572: Update based on implementation experimentation

This commit is contained in:
Chris Angelico 2018-04-13 21:34:33 +10:00
parent 5b8cf1da73
commit 5c2778d403
1 changed files with 27 additions and 4 deletions

View File

@ -35,9 +35,9 @@ Syntax and semantics
====================
In any context where arbitrary Python expressions can be used, a **named
expression** can appear. This can be parenthesized for clarity, and is of
the form ``(target := expr)`` where ``expr`` is any valid Python expression,
and ``target`` is any valid assignment target.
expression** can appear. This is of the form ``target := expr`` where
``expr`` is any valid Python expression, and ``target`` is any valid
assignment target. (NOTE: See 'Open questions' below for precedence.)
The value of such a named expression is the same as the incorporated
expression, with the additional side-effect that the target is assigned
@ -58,6 +58,9 @@ that value::
Differences from regular assignment statements
----------------------------------------------
Most importantly, since ``:=`` is an expression, it can be used in contexts
where statements are illegal, including lambda functions and comprehensions.
An assignment statement can assign to multiple targets::
x = y = z = 0
@ -232,7 +235,7 @@ Capturing condition values
Assignment expressions can be used to good effect in the header of
an ``if`` or ``while`` statement::
# Proposed alternative to the above
# Proposed syntax
while (command := input("> ")) != "quit":
print("You entered:", command)
@ -523,6 +526,26 @@ Translated into longhand, this would become::
ie utilizing the same early-binding technique that is used at class scope.
Operator precedence
-------------------
There are two logical precedences for the ``:=`` operator. Either it should
bind as loosely as possible, as does statement-assignment; or it should bind
more tightly than comparison operators. Placing its precedence between the
comparison and arithmetic operators (to be precise: just lower than bitwise
OR) allows most uses inside ``while`` and ``if`` conditions to be spelled
without parentheses, as it is most likely that you wish to capture the value
of something, then perform a comparison on it::
pos = -1
while pos := buffer.find(search_term, pos + 1) >= 0:
...
Once find() returns -1, the loop terminates. If ``:=`` binds as loosely as
``=`` does, this would capture the result of the comparison (generally either
``True`` or ``False``), which is less useful.
Frequently Raised Objections
============================