PEP 572: Weaken proposal / strengthen requirements from "target" to "name"

This commit is contained in:
Chris Angelico 2018-04-24 16:58:40 +10:00
parent 0f8a0669b4
commit 327d54250c
1 changed files with 19 additions and 8 deletions

View File

@ -35,9 +35,8 @@ Syntax and semantics
====================
In any context where arbitrary Python expressions can be used, a **named
expression** can appear. This 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 ``name := expr`` where
``expr`` is any valid Python expression, and ``name`` is an identifier.
The value of such a named expression is the same as the incorporated
expression, with the additional side-effect that the target is assigned
@ -70,6 +69,15 @@ and is therefore processed right-to-left, as if it were spelled thus::
assert 0 == (x := (y := (z := 0)))
Statement assignment can include annotations. This would be syntactically
noisy in expressions, and is of minor importance. An annotation can be
given separately from the assignment if needed::
x:str = "" # works
(x:str := "") # SyntaxError
x:str # possibly before a loop
(x := "") # fine
Augmented assignment is not supported in expression form::
>>> x +:= 1
@ -78,6 +86,10 @@ Augmented assignment is not supported in expression form::
^
SyntaxError: invalid syntax
Statement assignment is able to set attributes and subscripts, but
expression assignment is restricted to names. (This restriction may be
relaxed in a future version of Python.)
Otherwise, the semantics of assignment are identical in statement and
expression forms.
@ -522,8 +534,7 @@ With assignment expressions, why bother with assignment statements?
The two forms have different flexibilities. The ``:=`` operator can be used
inside a larger expression; the ``=`` statement can be augmented to ``+=`` and
its friends. The assignment statement is a clear declaration of intent: this
value is to be assigned to this target, and that's it.
its friends, can be chained, and can assign to attributes and subscripts.
Why not use a sublocal scope and prevent namespace pollution?
@ -550,9 +561,9 @@ suggestions to move the proposal in this direction. [2]_)
Style guide recommendations
===========================
As this adds another way to spell some of the same effects as can already be
done, it is worth noting a few broad recommendations. These could be included
in PEP 8 and/or other style guides.
As expression assignments can be used somewhat equivalently to statement
assignments, the question of which should be preferred will arise. For the
benefit of style guides such as PEP 8, two recommendations are suggested.
1. If either assignment statements or assignment expressions can be
used, prefer statements; they are a clear declaration of intent.