<div dir="ltr"><div><div dir="ltr"><div>A lot has been said about PEP 572. I am planning to accept it soon, hopefully within a week. I realize I should have posted the draft  from May 22 (when Tim and I were added as authors and it was significantly updated -- see <a href="https://github.com/python/peps/pull/654" target="_blank">https://github.com/python/<wbr>peps/pull/654</a>). For this I apologize. Since then we've been diligently updating various details, tightening the spec without really changing the intended design.</div><div><br></div><div>I know it is inevitable that there will be replies attempting to convince us that a different syntax is better or that we shouldn't do this at all. Please save your breath. Iv'e seen every possible such response before, and they haven't convinced me. At this point we're just looking for feedback on the text of the document, e.g. pointing out ambiguities or requests for more clarity in some part of the spec, *not* for alternative designs or passionate appeals to PEP 20.<br></div><div><br></div><div>Below is the latest draft. All three authors are happy with it. You can also read the PEP online at <a href="https://www.python.org/dev/peps/pep-0572/" target="_blank">https://www.python.org/dev/<wbr>peps/pep-0572/</a>. We strongly prefer feedback in the form of Pull Requests to the peps repo (the file is at <a href="https://github.com/python/peps/blob/master/pep-0572.rst" target="_blank">https://github.com/python/<wbr>peps/blob/master/pep-0572.rst</a>)<wbr>.</div><div><br></div><div><br></div><div>PEP: 572<br>Title: Assignment Expressions<br>Author: Chris Angelico <<a href="mailto:rosuav@gmail.com" target="_blank">rosuav@gmail.com</a>>, Tim Peters <<a href="mailto:tim.peters@gmail.com" target="_blank">tim.peters@gmail.com</a>>,<br>    Guido van Rossum <<a href="mailto:guido@python.org" target="_blank">guido@python.org</a>><br>Status: Draft<br>Type: Standards Track<br>Content-Type: text/x-rst<br>Created: 28-Feb-2018<br>Python-Version: 3.8<br>Post-History: 28-Feb-2018, 02-Mar-2018, 23-Mar-2018, 04-Apr-2018, 17-Apr-2018,<br>              25-Apr-2018, 09-Jul-2018<br><br><br>Abstract<br>========<br><br>This is a proposal for creating a way to assign to variables within an<br>expression using the notation ``NAME := expr``.<br><br>Pending Acceptance<br>------------------<br><br>This PEP will be accepted, however it needs some editing for clarity<br>and exact specification.  A final draft will be posted to python-dev.<br>Note that alternate syntax proposals ("EXPR as NAME", "EXPR given<br>...") are no longer under consideration.  Hopefully the final draft<br>will be posted well before the end of July 2018.<br><br><br>Rationale<br>=========<br><br>Naming the result of an expression is an important part of programming,<br>allowing a descriptive name to be used in place of a longer expression,<br>and permitting reuse.  Currently, this feature is available only in<br>statement form, making it unavailable in list comprehensions and other<br>expression contexts.<br><br>Additionally, naming sub-parts of a large expression can assist an interactive<br>debugger, providing useful display hooks and partial results. Without a way to<br>capture sub-expressions inline, this would require refactoring of the original<br>code; with assignment expressions, this merely requires the insertion of a few<br>``name :=`` markers. Removing the need to refactor reduces the likelihood that<br>the code be inadvertently changed as part of debugging (a common cause of<br>Heisenbugs), and is easier to dictate to another programmer.<br><br>The importance of real code<br>---------------------------<br><br>During the development of this PEP many people (supporters and critics<br>both) have had a tendency to focus on toy examples on the one hand,<br>and on overly complex examples on the other.<br><br>The danger of toy examples is twofold: they are often too abstract to<br>make anyone go "ooh, that's compelling", and they are easily refuted<br>with "I would never write it that way anyway".<br><br>The danger of overly complex examples is that they provide a<br>convenient strawman for critics of the proposal to shoot down ("that's<br>obfuscated").<br><br>Yet there is some use for both extremely simple and extremely complex<br>examples: they are helpful to clarify the intended semantics.<br>Therefore there will be some of each below.<br><br>However, in order to be *compelling*, examples should be rooted in<br>real code, i.e. code that was written without any thought of this PEP,<br>as part of a useful application, however large or small.  Tim Peters<br>has been extremely helpful by going over his own personal code<br>repository and picking examples of code he had written that (in his<br>view) would have been *clearer* if rewritten with (sparing) use of<br>assignment expressions.  His conclusion: the current proposal would<br>have allowed a modest but clear improvement in quite a few bits of<br>code.<br><br>Another use of real code is to observe indirectly how much value<br>programmers place on compactness.  Guido van Rossum searched through a<br>Dropbox code base and discovered some evidence that programmers value<br>writing fewer lines over shorter lines.<br><br>Case in point: Guido found several examples where a programmer<br>repeated a subexpression, slowing down the program, in order to save<br>one line of code, e.g. instead of writing::<br><br>    match = re.match(data)<br>    group = match.group(1) if match else None<br><br>they would write::<br><br>    group = re.match(data).group(1) if re.match(data) else None<br><br>Another example illustrates that programmers sometimes do more work to<br>save an extra level of indentation::<br><br>    match1 = pattern1.match(data)<br>    match2 = pattern2.match(data)<br>    if match1:<br>        return match1.group(1)<br>    elif match2:<br>        return match2.group(2)<br><br>This code tries to match ``pattern2`` even if ``pattern1`` has a match<br>(in which case the match on ``pattern2`` is never used).  The more<br>efficient rewrite would have been::<br><br>    match1 = pattern1.match(data)<br>    if match1:<br>        return match1.group(1)<br>    else:<br>        match2 = pattern2.match(data)<br>        if match2:<br>            return match2.group(2)<br><br><br>Syntax and semantics<br>====================<br><br>In most contexts where arbitrary Python expressions can be used, a<br>**named expression** can appear.  This is of the form ``NAME := expr``<br>where ``expr`` is any valid Python expression other than an<br>unparenthesized tuple, and ``NAME`` is an identifier.<br><br>The value of such a named expression is the same as the incorporated<br>expression, with the additional side-effect that the target is assigned<br>that value::<br><br>    # Handle a matched regex<br>    if (match := pattern.search(data)) is not None:<br>        ...<br><br>    # A more explicit alternative to the 2-arg form of iter() invocation<br>    while (value := read_next_item()) is not None:<br>        ...<br><br>    # Share a subexpression between a comprehension filter clause and its output<br>    filtered_data = [y for x in data if (y := f(x)) is not None]<br><br>Exceptional cases<br>-----------------<br><br>There are a few places where assignment expressions are not allowed,<br>in order to avoid ambiguities or user confusion:<br><br>- Unparenthesized assignment expressions are prohibited at the top<br>  level of an expression statement.  Example::<br><br>    y := f(x)  # INVALID<br>    (y := f(x))  # Valid, though not recommended<br><br>  This rule is included to simplify the choice for the user between an<br>  assignment statements and an assignment expression -- there is no<br>  syntactic position where both are valid.<br><br>- Unparenthesized assignment expressions are prohibited at the top<br>  level of the right hand side of an assignment statement.  Example::<br><br>    y0 = y1 := f(x)  # INVALID<br>    y0 = (y1 := f(x))  # Valid, though discouraged<br><br>  Again, this rule is included to avoid two visually similar ways of<br>  saying the same thing.<br><br>- Unparenthesized assignment expressions are prohibited for the value<br>  of a keyword argument in a call.  Example::<br><br>    foo(x = y := f(x))  # INVALID<br>    foo(x=(y := f(x)))  # Valid, though probably confusing<br><br>  This rule is included to disallow excessively confusing code, and<br>  because parsing keyword arguments is complex enough already.<br><br>- Unparenthesized assignment expressions are prohibited at the top<br>  level of a function default value.  Example::<br><br>    def foo(answer = p := 42):  # INVALID<br>        ...<br>    def foo(answer=(p := 42)):  # Valid, though not great style<br>        ...<br><br>  This rule is included to discourage side effects in a position whose<br>  exact semantics are already confusing to many users (cf. the common<br>  style recommendation against mutable default values), and also to<br>  echo the similar prohibition in calls (the previous bullet).<br><br>Scope of the target<br>-------------------<br><br>An assignment expression does not introduce a new scope.  In most<br>cases the scope in which the target will be bound is self-explanatory:<br>it is the current scope.  If this scope contains a ``nonlocal`` or<br>``global`` declaration for the target, the assignment expression<br>honors that.  A lambda (being an explicit, if anonymous, function<br>definition) counts as a scope for this purpose.<br><br>There is one special case: an assignment expression occurring in a<br>list, set or dict comprehension or in a generator expression (below<br>collectively referred to as "comprehensions") binds the target in the<br>containing scope, honoring a ``nonlocal`` or ``global`` declaration<br>for the target in that scope, if one exists.  For the purpose of this<br>rule the containing scope of a nested comprehension is the scope that<br>contains the outermost comprehension.  A lambda counts as a containing<br>scope.<br><br>The motivation for this special case is twofold.  First, it allows us<br>to conveniently capture a "witness" for an ``any()`` expression, or a<br>counterexample for ``all()``, for example::<br><br>    if any((comment := line).startswith('#') for line in lines):<br>        print("First comment:", comment)<br>    else:<br>        print("There are no comments")<br><br>    if all((nonblank := line).strip() == '' for line in lines):<br>        print("All lines are blank")<br>    else:<br>        print("First non-blank line:", nonblank)<br><br>Second, it allows a compact way of updating mutable state from a<br>comprehension, for example::<br><br>    # Compute partial sums in a list comprehension<br>    total = 0<br>    partial_sums = [total := total + v for v in values]<br>    print("Total:", total)<br><br>An exception to this special case applies when the target name is the<br>same as a loop control variable for a comprehension containing it.<br>This is invalid.  This exception exists to rule out edge cases of the<br>above scope rules as illustrated by ``[i := i+1 for i in range(5)]``<br>or ``[[(j := j) for i in range(5)] for j in range(5)]``.  Note that<br>this exception also applies to ``[i := 0 for i, j in stuff]``, as well<br>as to cases like ``[i+1 for i in i := stuff]``.<br><br>A further exception applies when an assignment expression occurrs in a<br>comprehension whose containing scope is a class scope.  If the rules<br>above were to result in the target being assigned in that class's<br>scope, the assignment expression is expressly invalid.<br><br>(The reason for the latter exception is the implicit function created<br>for comprehensions -- there is currently no runtime mechanism for a<br>function to refer to a variable in the containing class scope, and we<br>do not want to add such a mechanism.  If this issue ever gets resolved<br>this special case may be removed from the specification of assignment<br>expressions.  Note that the problem already exists for *using* a<br>variable defined in the class scope from a comprehension.)<br><br>See Appendix B for some examples of how the rules for targets in<br>comprehensions translate to equivalent code.<br><br>The two invalid cases listed above raise ``TargetScopeError``, a<br>subclass of ``SyntaxError`` (with the same signature).<br><br>Relative precedence of ``:=``<br>-----------------------------<br><br>The ``:=`` operator groups more tightly than a comma in all syntactic<br>positions where it is legal, but less tightly than all operators,<br>including ``or``, ``and`` and ``not``.  As follows from section<br>"Exceptional cases" above, it is never allowed at the same level as<br>``=``.  In case a different grouping is desired, parentheses should be<br>used.<br><br>The ``:=`` operator may be used directly in a positional function call<br>argument; however it is invalid directly in a keyword argument.<br><br>Some examples to clarify what's technically valid or invalid::<br><br>    # INVALID<br>    x := 0<br><br>    # Valid alternative<br>    (x := 0)<br><br>    # INVALID<br>    x = y := 0<br><br>    # Valid alternative<br>    x = (y := 0)<br><br>    # Valid<br>    len(lines := f.readlines())<br><br>    # Valid<br>    foo(x := 3, cat='vector')<br><br>    # INVALID<br>    foo(cat=category := 'vector')<br><br>    # Valid alternative<br>    foo(cat=(category := 'vector'))<br><br>Most of the "valid" examples above are not recommended, since human<br>readers of Python source code who are quickly glancing at some code<br>may miss the distinction.  But simple cases are not objectionable::<br><br>    # Valid<br>    if any(len(longline := line) >= 100 for line in lines):<br>        print("Extremely long line:", longline)<br><br>This PEP recommends always putting spaces around ``:=``, similar to<br>PEP 8's recommendation for ``=`` when used for assignment, whereas the<br>latter disallows spaces around ``=`` used for keyword arguments.)<br><br>Change to evaluation order<br>--------------------------<br><br>In order to have precisely defined semantics, the proposal requires<br>evaluation order to be well-defined.  This is technically not a new<br>requirement, as function calls may already have side effects.  Python<br>already has a rule that subexpressions are generally evaluated from<br>left to right.  However, assignment expressions make these side<br>effects more visible, and we propose a single change to the current<br>evaluation order:<br><br>- In a dict comprehension ``{X: Y for ...}``, ``Y`` is currently<br>  evaluated before ``X``.  We propose to change this so that ``X`` is<br>  evaluated before ``Y``.  (In a dict display like ``{X: Y}}`` this is<br>  already the case, and also in ``dict((X, Y) for ...)`` which should<br>  clearly be equivalent to the dict comprehension.)<br><br>Differences between  assignment expressions and assignment statements<br>------------------------------<wbr>------------------------------<wbr>---------<br><br>Most importantly, since ``:=`` is an expression, it can be used in contexts<br>where statements are illegal, including lambda functions and comprehensions.<br><br>Conversely, assignment expressions don't support the advanced features<br>found in assignment statements:<br><br>- Multiple targets are not directly supported::<br><br>    x = y = z = 0  # Equivalent: (z := (y := (x := 0)))<br><br>- Single assignment targets other than than a single ``NAME`` are<br>  not supported::<br><br>    # No equivalent<br>    a[i] = x<br>    self.rest = []<br><br>- Priority around commas is different::<br><br>    x = 1, 2  # Sets x to (1, 2)<br>    (x := 1, 2)  # Sets x to 1<br><br>- Iterable packing and unpacking (both regular or extended forms) are<br>  not supported::<br><br>    # Equivalent needs extra parentheses<br>    loc = x, y  # Use (loc := (x, y))<br>    info = name, phone, *rest  # Use (info := (name, phone, *rest))<br><br>    # No equivalent<br>    px, py, pz = position<br>    name, phone, email, *other_info = contact<br><br>- Type annotations are not supported::<br><br>    # No equivalent<br>    p: Optional[int] = None<br><br>- Augmented assignment is not supported::<br><br>    total += tax  # Equivalent: (total := total + tax)<br><br><br>Examples<br>========<br><br>Examples from the Python standard library<br>------------------------------<wbr>-----------<br><br>site.py<br>^^^^^^^<br><br>*env_base* is only used on these lines, putting its assignment on the if<br>moves it as the "header" of the block.<br><br>- Current::<br><br>    env_base = os.environ.get("<wbr>PYTHONUSERBASE", None)<br>    if env_base:<br>        return env_base<br><br>- Improved::<br><br>    if env_base := os.environ.get("<wbr>PYTHONUSERBASE", None):<br>        return env_base<br><br>_pydecimal.py<br>^^^^^^^^^^^^^<br><br>Avoid nested if and remove one indentation level.<br><br>- Current::<br><br>    if self._is_special:<br>        ans = self._check_nans(context=<wbr>context)<br>        if ans:<br>            return ans<br><br>- Improved::<br><br>    if self._is_special and (ans := self._check_nans(context=<wbr>context)):<br>        return ans<br><br>copy.py<br>^^^^^^^<br><br>Code looks more regular and avoid multiple nested if.<br>(See Appendix A for the origin of this example.)<br><br>- Current::<br><br>    reductor = dispatch_table.get(cls)<br>    if reductor:<br>        rv = reductor(x)<br>    else:<br>        reductor = getattr(x, "__reduce_ex__", None)<br>        if reductor:<br>            rv = reductor(4)<br>        else:<br>            reductor = getattr(x, "__reduce__", None)<br>            if reductor:<br>                rv = reductor()<br>            else:<br>                raise Error(<br>                    "un(deep)copyable object of type %s" % cls)<br><br>- Improved::<br><br>    if reductor := dispatch_table.get(cls):<br>        rv = reductor(x)<br>    elif reductor := getattr(x, "__reduce_ex__", None):<br>        rv = reductor(4)<br>    elif reductor := getattr(x, "__reduce__", None):<br>        rv = reductor()<br>    else:<br>        raise Error("un(deep)copyable object of type %s" % cls)<br><br>datetime.py<br>^^^^^^^^^^^<br><br>*tz* is only used for ``s += tz``, moving its assignment inside the if<br>helps to show its scope.<br><br>- Current::<br><br>    s = _format_time(self._hour, self._minute,<br>                     self._second, self._microsecond,<br>                     timespec)<br>    tz = self._tzstr()<br>    if tz:<br>        s += tz<br>    return s<br><br>- Improved::<br><br>    s = _format_time(self._hour, self._minute,<br>                     self._second, self._microsecond,<br>                     timespec)<br>    if tz := self._tzstr():<br>        s += tz<br>    return s<br><br>sysconfig.py<br>^^^^^^^^^^^^<br><br>Calling ``fp.readline()`` in the ``while`` condition and calling<br>``.match()`` on the if lines make the code more compact without making<br>it harder to understand.<br><br>- Current::<br><br>    while True:<br>        line = fp.readline()<br>        if not line:<br>            break<br>        m = define_rx.match(line)<br>        if m:<br>            n, v = m.group(1, 2)<br>            try:<br>                v = int(v)<br>            except ValueError:<br>                pass<br>            vars[n] = v<br>        else:<br>            m = undef_rx.match(line)<br>            if m:<br>                vars[m.group(1)] = 0<br><br>- Improved::<br><br>    while line := fp.readline():<br>        if m := define_rx.match(line):<br>            n, v = m.group(1, 2)<br>            try:<br>                v = int(v)<br>            except ValueError:<br>                pass<br>            vars[n] = v<br>        elif m := undef_rx.match(line):<br>            vars[m.group(1)] = 0<br><br><br>Simplifying list comprehensions<br>------------------------------<wbr>-<br><br>A list comprehension can map and filter efficiently by capturing<br>the condition::<br><br>    results = [(x, y, x/y) for x in input_data if (y := f(x)) > 0]<br><br>Similarly, a subexpression can be reused within the main expression, by<br>giving it a name on first use::<br><br>    stuff = [[y := f(x), x/y] for x in range(5)]<br><br>Note that in both cases the variable ``y`` is bound in the containing<br>scope (i.e. at the same level as ``results`` or ``stuff``).<br><br><br>Capturing condition values<br>--------------------------<br><br>Assignment expressions can be used to good effect in the header of<br>an ``if`` or ``while`` statement::<br><br>    # Loop-and-a-half<br>    while (command := input("> ")) != "quit":<br>        print("You entered:", command)<br><br>    # Capturing regular expression match objects<br>    # See, for instance, Lib/pydoc.py, which uses a multiline spelling<br>    # of this effect<br>    if match := re.search(pat, text):<br>        print("Found:", match.group(0))<br>    # The same syntax chains nicely into 'elif' statements, unlike the<br>    # equivalent using assignment statements.<br>    elif match := re.search(otherpat, text):<br>        print("Alternate found:", match.group(0))<br>    elif match := re.search(third, text):<br>        print("Fallback found:", match.group(0))<br><br>    # Reading socket data until an empty string is returned<br>    while data := sock.recv():<br>        print("Received data:", data)<br><br>Particularly with the ``while`` loop, this can remove the need to have an<br>infinite loop, an assignment, and a condition. It also creates a smooth<br>parallel between a loop which simply uses a function call as its condition,<br>and one which uses that as its condition but also uses the actual value.<br><br>Fork<br>----<br><br>An example from the low-level UNIX world::<br><br>    if pid := os.fork():<br>        # Parent code<br>    else:<br>        # Child code<br><br><br>Rejected alternative proposals<br>==============================<br><br>Proposals broadly similar to this one have come up frequently on python-ideas.<br>Below are a number of alternative syntaxes, some of them specific to<br>comprehensions, which have been rejected in favour of the one given above.<br><br><br>Changing the scope rules for comprehensions<br>------------------------------<wbr>-------------<br><br>A previous version of this PEP proposed subtle changes to the scope<br>rules for comprehensions, to make them more usable in class scope and<br>to unify the scope of the "outermost iterable" and the rest of the<br>comprehension.  However, this part of the proposal would have caused<br>backwards incompatibilities, and has been withdrawn so the PEP can<br>focus on assignment expressions.<br><br><br>Alternative spellings<br>---------------------<br><br>Broadly the same semantics as the current proposal, but spelled differently.<br><br>1. ``EXPR as NAME``::<br><br>       stuff = [[f(x) as y, x/y] for x in range(5)]<br><br>   Since ``EXPR as NAME`` already has meaning in ``import``,<br>   ``except`` and ``with`` statements (with different semantics), this<br>   would create unnecessary confusion or require special-casing<br>   (e.g. to forbid assignment within the headers of these statements).<br><br>   (Note that ``with EXPR as VAR`` does *not* simply assing the value<br>   of ``EXPR`` to ``VAR`` -- it calls ``EXPR.__enter__()`` and assigns<br>   the result of *that* to ``VAR``.)<br><br>   Additional reasons to prefer ``:=`` over this spelling include:<br><br>   - In ``if f(x) as y`` the assignment target doesn't jump out at you<br>     -- it just reads like ``if f x blah blah`` and it is too similar<br>     visually to ``if f(x) and y``.<br><br>   - In all other situations where an ``as`` clause is allowed, even<br>     readers with intermediary skills are led to anticipate that<br>     clause (however optional) by the keyword that starts the line,<br>     and the grammar ties that keyword closely to the as clause:<br><br>     - ``import foo as bar``<br>     - ``except Exc as var``<br>     - ``with ctxmgr() as var``<br><br>     To the contrary, the assignment expression does not belong to the<br>     ``if`` or ``while`` that starts the line, and we intentionally<br>     allow assignment expressions in other contexts as well.<br><br>   - The parallel cadence between<br><br>     - ``NAME = EXPR``<br>     - ``if NAME := EXPR``<br><br>     reinforces the visual recognition of assignment expressions.<br><br>2. ``EXPR -> NAME``::<br><br>       stuff = [[f(x) -> y, x/y] for x in range(5)]<br><br>   This syntax is inspired by languages such as R and Haskell, and some<br>   programmable calculators. (Note that a left-facing arrow ``y <- f(x)`` is<br>   not possible in Python, as it would be interpreted as less-than and unary<br>   minus.) This syntax has a slight advantage over 'as' in that it does not<br>   conflict with ``with``, ``except`` and ``import``, but otherwise is<br>   equivalent.  But it is entirely unrelated to Python's other use of<br>   ``->`` (function return type annotations), and compared to ``:=``<br>   (which dates back to Algol-58) it has a much weaker tradition.<br><br>3. Adorning statement-local names with a leading dot::<br><br>       stuff = [[(f(x) as .y), x/.y] for x in range(5)] # with "as"<br>       stuff = [[(.y := f(x)), x/.y] for x in range(5)] # with ":="<br><br>   This has the advantage that leaked usage can be readily detected, removing<br>   some forms of syntactic ambiguity.  However, this would be the only place<br>   in Python where a variable's scope is encoded into its name, making<br>   refactoring harder.<br><br>4. Adding a ``where:`` to any statement to create local name bindings::<br><br>       value = x**2 + 2*x where:<br>           x = spam(1, 4, 7, q)<br><br>   Execution order is inverted (the indented body is performed first, followed<br>   by the "header").  This requires a new keyword, unless an existing keyword<br>   is repurposed (most likely ``with:``).  See PEP 3150 for prior discussion<br>   on this subject (with the proposed keyword being ``given:``).<br><br>5. ``TARGET from EXPR``::<br><br>       stuff = [[y from f(x), x/y] for x in range(5)]<br><br>   This syntax has fewer conflicts than ``as`` does (conflicting only with the<br>   ``raise Exc from Exc`` notation), but is otherwise comparable to it. Instead<br>   of paralleling ``with expr as target:`` (which can be useful but can also be<br>   confusing), this has no parallels, but is evocative.<br><br><br>Special-casing conditional statements<br>------------------------------<wbr>-------<br><br>One of the most popular use-cases is ``if`` and ``while`` statements.  Instead<br>of a more general solution, this proposal enhances the syntax of these two<br>statements to add a means of capturing the compared value::<br><br>    if re.search(pat, text) as match:<br>        print("Found:", match.group(0))<br><br>This works beautifully if and ONLY if the desired condition is based on the<br>truthiness of the captured value.  It is thus effective for specific<br>use-cases (regex matches, socket reads that return `''` when done), and<br>completely useless in more complicated cases (eg where the condition is<br>``f(x) < 0`` and you want to capture the value of ``f(x)``).  It also has<br>no benefit to list comprehensions.<br><br>Advantages: No syntactic ambiguities. Disadvantages: Answers only a fraction<br>of possible use-cases, even in ``if``/``while`` statements.<br><br><br>Special-casing comprehensions<br>-----------------------------<br><br>Another common use-case is comprehensions (list/set/dict, and genexps). As<br>above, proposals have been made for comprehension-specific solutions.<br><br>1. ``where``, ``let``, or ``given``::<br><br>       stuff = [(y, x/y) where y = f(x) for x in range(5)]<br>       stuff = [(y, x/y) let y = f(x) for x in range(5)]<br>       stuff = [(y, x/y) given y = f(x) for x in range(5)]<br><br>   This brings the subexpression to a location in between the 'for' loop and<br>   the expression. It introduces an additional language keyword, which creates<br>   conflicts. Of the three, ``where`` reads the most cleanly, but also has the<br>   greatest potential for conflict (eg SQLAlchemy and numpy have ``where``<br>   methods, as does ``tkinter.dnd.Icon`` in the standard library).<br><br>2. ``with NAME = EXPR``::<br><br>       stuff = [(y, x/y) with y = f(x) for x in range(5)]<br><br>   As above, but reusing the `with` keyword. Doesn't read too badly, and needs<br>   no additional language keyword. Is restricted to comprehensions, though,<br>   and cannot as easily be transformed into "longhand" for-loop syntax. Has<br>   the C problem that an equals sign in an expression can now create a name<br>   binding, rather than performing a comparison. Would raise the question of<br>   why "with NAME = EXPR:" cannot be used as a statement on its own.<br><br>3. ``with EXPR as NAME``::<br><br>       stuff = [(y, x/y) with f(x) as y for x in range(5)]<br><br>   As per option 2, but using ``as`` rather than an equals sign. Aligns<br>   syntactically with other uses of ``as`` for name binding, but a simple<br>   transformation to for-loop longhand would create drastically different<br>   semantics; the meaning of ``with`` inside a comprehension would be<br>   completely different from the meaning as a stand-alone statement, while<br>   retaining identical syntax.<br><br>Regardless of the spelling chosen, this introduces a stark difference between<br>comprehensions and the equivalent unrolled long-hand form of the loop.  It is<br>no longer possible to unwrap the loop into statement form without reworking<br>any name bindings.  The only keyword that can be repurposed to this task is<br>``with``, thus giving it sneakily different semantics in a comprehension than<br>in a statement; alternatively, a new keyword is needed, with all the costs<br>therein.<br><br><br>Lowering operator precedence<br>----------------------------<br><br>There are two logical precedences for the ``:=`` operator. Either it should<br>bind as loosely as possible, as does statement-assignment; or it should bind<br>more tightly than comparison operators. Placing its precedence between the<br>comparison and arithmetic operators (to be precise: just lower than bitwise<br>OR) allows most uses inside ``while`` and ``if`` conditions to be spelled<br>without parentheses, as it is most likely that you wish to capture the value<br>of something, then perform a comparison on it::<br><br>    pos = -1<br>    while pos := buffer.find(search_term, pos + 1) >= 0:<br>        ...<br><br>Once find() returns -1, the loop terminates. If ``:=`` binds as loosely as<br>``=`` does, this would capture the result of the comparison (generally either<br>``True`` or ``False``), which is less useful.<br><br>While this behaviour would be convenient in many situations, it is also harder<br>to explain than "the := operator behaves just like the assignment statement",<br>and as such, the precedence for ``:=`` has been made as close as possible to<br>that of ``=`` (with the exception that it binds tighter than comma).<br><br><br>Allowing commas to the right<br>----------------------------<br><br>Some critics have claimed that the assignment expressions should allow<br>unparenthesized tuples on the right, so that these two would be equivalent::<br><br>    (point := (x, y))<br>    (point := x, y)<br><br>(With the current version of the proposal, the latter would be<br>equivalent to ``((point := x), y)``.)<br><br>However, adopting this stance would logically lead to the conclusion<br>that when used in a function call, assignment expressions also bind<br>less tight than comma, so we'd have the following confusing equivalence::<br><br>    foo(x := 1, y)<br>    foo(x := (1, y))<br><br>The less confusing option is to make ``:=`` bind more tightly than comma.<br><br><br>Always requiring parentheses<br>----------------------------<br><br>It's been proposed to just always require parenthesize around an<br>assignment expression.  This would resolve many ambiguities, and<br>indeed parentheses will frequently be needed to extract the desired<br>subexpression.  But in the following cases the extra parentheses feel<br>redundant::<br><br>    # Top level in if<br>    if match := pattern.match(line):<br>        return match.group(1)<br><br>    # Short call<br>    len(lines := f.readlines())<br><br><br>Frequently Raised Objections<br>============================<br><br>Why not just turn existing assignment into an expression?<br>------------------------------<wbr>---------------------------<br><br>C and its derivatives define the ``=`` operator as an expression, rather than<br>a statement as is Python's way.  This allows assignments in more contexts,<br>including contexts where comparisons are more common.  The syntactic similarity<br>between ``if (x == y)`` and ``if (x = y)`` belies their drastically different<br>semantics.  Thus this proposal uses ``:=`` to clarify the distinction.<br><br><br>This could be used to create ugly code!<br>------------------------------<wbr>---------<br><br>So can anything else.  This is a tool, and it is up to the programmer to use it<br>where it makes sense, and not use it where superior constructs can be used.<br><br><br>With assignment expressions, why bother with assignment statements?<br>------------------------------<wbr>------------------------------<wbr>-------<br><br>The two forms have different flexibilities.  The ``:=`` operator can be used<br>inside a larger expression; the ``=`` statement can be augmented to ``+=`` and<br>its friends, can be chained, and can assign to attributes and subscripts.<br><br><br>Why not use a sublocal scope and prevent namespace pollution?<br>------------------------------<wbr>------------------------------<wbr>-<br><br>Previous revisions of this proposal involved sublocal scope (restricted to a<br>single statement), preventing name leakage and namespace pollution.  While a<br>definite advantage in a number of situations, this increases complexity in<br>many others, and the costs are not justified by the benefits. In the interests<br>of language simplicity, the name bindings created here are exactly equivalent<br>to any other name bindings, including that usage at class or module scope will<br>create externally-visible names.  This is no different from ``for`` loops or<br>other constructs, and can be solved the same way: ``del`` the name once it is<br>no longer needed, or prefix it with an underscore.<br><br>(The author wishes to thank Guido van Rossum and Christoph Groth for their<br>suggestions to move the proposal in this direction. [2]_)<br><br><br>Style guide recommendations<br>===========================<br><br>As expression assignments can sometimes be used equivalently to statement<br>assignments, the question of which should be preferred will arise. For the<br>benefit of style guides such as PEP 8, two recommendations are suggested.<br><br>1. If either assignment statements or assignment expressions can be<br>   used, prefer statements; they are a clear declaration of intent.<br><br>2. If using assignment expressions would lead to ambiguity about<br>   execution order, restructure it to use statements instead.<br><br><br>Acknowledgements<br>================<br><br>The authors wish to thank Nick Coghlan and Steven D'Aprano for their<br>considerable contributions to this proposal, and members of the<br>core-mentorship mailing list for assistance with implementation.<br><br><br>Appendix A: Tim Peters's findings<br>==============================<wbr>===<br><br>Here's a brief essay Tim Peters wrote on the topic.<br><br>I dislike "busy" lines of code, and also dislike putting conceptually<br>unrelated logic on a single line.  So, for example, instead of::<br><br>    i = j = count = nerrors = 0<br><br>I prefer::<br><br>    i = j = 0<br>    count = 0<br>    nerrors = 0<br><br>instead.  So I suspected I'd find few places I'd want to use<br>assignment expressions.  I didn't even consider them for lines already<br>stretching halfway across the screen.  In other cases, "unrelated"<br>ruled::<br><br>    mylast = mylast[1]<br>    yield mylast[0]<br><br>is a vast improvment over the briefer::<br><br>    yield (mylast := mylast[1])[0]<br><br>The original two statements are doing entirely different conceptual<br>things, and slamming them together is conceptually insane.<br><br>In other cases, combining related logic made it harder to understand,<br>such as rewriting::<br><br>    while True:<br>        old = total<br>        total += term<br>        if old == total:<br>            return total<br>        term *= mx2 / (i*(i+1))<br>        i += 2<br><br>as the briefer::<br><br>    while total != (total := total + term):<br>        term *= mx2 / (i*(i+1))<br>        i += 2<br>    return total<br><br>The ``while`` test there is too subtle, crucially relying on strict<br>left-to-right evaluation in a non-short-circuiting or method-chaining<br>context.  My brain isn't wired that way.<br><br>But cases like that were rare.  Name binding is very frequent, and<br>"sparse is better than dense" does not mean "almost empty is better<br>than sparse".  For example, I have many functions that return ``None``<br>or ``0`` to communicate "I have nothing useful to return in this case,<br>but since that's expected often I'm not going to annoy you with an<br>exception".  This is essentially the same as regular expression search<br>functions returning ``None`` when there is no match.  So there was lots<br>of code of the form::<br><br>    result = solution(xs, n)<br>    if result:<br>        # use result<br><br>I find that clearer, and certainly a bit less typing and<br>pattern-matching reading, as::<br><br>    if result := solution(xs, n):<br>        # use result<br><br>It's also nice to trade away a small amount of horizontal whitespace<br>to get another _line_ of surrounding code on screen.  I didn't give<br>much weight to this at first, but it was so very frequent it added up,<br>and I soon enough became annoyed that I couldn't actually run the<br>briefer code.  That surprised me!<br><br>There are other cases where assignment expressions really shine.<br>Rather than pick another from my code, Kirill Balunov gave a lovely<br>example from the standard library's ``copy()`` function in ``copy.py``::<br><br>    reductor = dispatch_table.get(cls)<br>    if reductor:<br>        rv = reductor(x)<br>    else:<br>        reductor = getattr(x, "__reduce_ex__", None)<br>        if reductor:<br>            rv = reductor(4)<br>        else:<br>            reductor = getattr(x, "__reduce__", None)<br>            if reductor:<br>                rv = reductor()<br>            else:<br>                raise Error("un(shallow)copyable object of type %s" % cls)<br><br>The ever-increasing indentation is semantically misleading: the logic<br>is conceptually flat, "the first test that succeeds wins"::<br><br>    if reductor := dispatch_table.get(cls):<br>        rv = reductor(x)<br>    elif reductor := getattr(x, "__reduce_ex__", None):<br>        rv = reductor(4)<br>    elif reductor := getattr(x, "__reduce__", None):<br>        rv = reductor()<br>    else:<br>        raise Error("un(shallow)copyable object of type %s" % cls)<br><br>Using easy assignment expressions allows the visual structure of the<br>code to emphasize the conceptual flatness of the logic;<br>ever-increasing indentation obscured it.<br><br>A smaller example from my code delighted me, both allowing to put<br>inherently related logic in a single line, and allowing to remove an<br>annoying "artificial" indentation level::<br><br>    diff = x - x_base<br>    if diff:<br>        g = gcd(diff, n)<br>        if g > 1:<br>            return g<br><br>became::<br><br>    if (diff := x - x_base) and (g := gcd(diff, n)) > 1:<br>        return g<br><br>That ``if`` is about as long as I want my lines to get, but remains easy<br>to follow.<br><br>So, in all, in most lines binding a name, I wouldn't use assignment<br>expressions, but because that construct is so very frequent, that<br>leaves many places I would.  In most of the latter, I found a small<br>win that adds up due to how often it occurs, and in the rest I found a<br>moderate to major win.  I'd certainly use it more often than ternary<br>``if``, but significantly less often than augmented assignment.<br><br>A numeric example<br>-----------------<br><br>I have another example that quite impressed me at the time.<br><br>Where all variables are positive integers, and a is at least as large<br>as the n'th root of x, this algorithm returns the floor of the n'th<br>root of x (and roughly doubling the number of accurate bits per<br>iteration)::<br><br>    while a > (d := x // a**(n-1)):<br>        a = ((n-1)*a + d) // n<br>    return a<br><br>It's not obvious why that works, but is no more obvious in the "loop<br>and a half" form. It's hard to prove correctness without building on<br>the right insight (the "arithmetic mean - geometric mean inequality"),<br>and knowing some non-trivial things about how nested floor functions<br>behave. That is, the challenges are in the math, not really in the<br>coding.<br><br>If you do know all that, then the assignment-expression form is easily<br>read as "while the current guess is too large, get a smaller guess",<br>where the "too large?" test and the new guess share an expensive<br>sub-expression.<br><br>To my eyes, the original form is harder to understand::<br><br>    while True:<br>        d = x // a**(n-1)<br>        if a <= d:<br>            break<br>        a = ((n-1)*a + d) // n<br>    return a<br><br><br>Appendix B: Rough code translations for comprehensions<br>==============================<wbr>========================<br><br>This appendix attempts to clarify (though not specify) the rules when<br>a target occurs in a comprehension or in a generator expression.<br>For a number of illustrative examples we show the original code,<br>containing a comprehension, and the translation, where the<br>comprehension has been replaced by an equivalent generator function<br>plus some scaffolding.<br><br>Since ``[x for ...]`` is equivalent to ``list(x for ...)`` these<br>examples all use list comprehensions without loss of generality.<br>And since these examples are meant to clarify edge cases of the rules,<br>they aren't trying to look like real code.<br><br>Note: comprehensions are already implemented via synthesizing nested<br>generator functions like those in this appendix.  The new part is<br>adding appropriate declarations to establish the intended scope of<br>assignment expression targets (the same scope they resolve to as if<br>the assignment were performed in the block containing the outermost<br>comprehension).  For type inference purposes, these illustrative<br>expansions do not imply that assignment expression targets are always<br>Optional (but they do indicate the target binding scope).<br><br>Let's start with a reminder of what code is generated for a generator<br>expression without assignment expression.<br><br>- Original code (EXPR usually references VAR)::<br><br>    def f():<br>        a = [EXPR for VAR in ITERABLE]<br><br>- Translation (let's not worry about name conflicts)::<br><br>    def f():<br>        def genexpr(iterator):<br>            for VAR in iterator:<br>                yield EXPR<br>        a = list(genexpr(iter(ITERABLE)))<br><br>Let's add a simple assignment expression.<br><br>- Original code::<br><br>    def f():<br>        a = [TARGET := EXPR for VAR in ITERABLE]<br><br>- Translation::<br><br>    def f():<br>        if False:<br>            TARGET = None  # Dead code to ensure TARGET is a local variable<br>        def genexpr(iterator):<br>            nonlocal TARGET<br>            for VAR in iterator:<br>                TARGET = EXPR<br>                yield TARGET<br>        a = list(genexpr(iter(ITERABLE)))<br><br>Let's add a ``global TARGET`` declaration in ``f()``.<br><br>- Original code::<br><br>    def f():<br>        global TARGET<br>        a = [TARGET := EXPR for VAR in ITERABLE]<br><br>- Translation::<br><br>    def f():<br>        global TARGET<br>        def genexpr(iterator):<br>            global TARGET<br>            for VAR in iterator:<br>                TARGET = EXPR<br>                yield TARGET<br>        a = list(genexpr(iter(ITERABLE)))<br><br>Or instead let's add a ``nonlocal TARGET`` declaration in ``f()``.<br><br>- Original code::<br><br>    def g():<br>        TARGET = ...<br>        def f():<br>            nonlocal TARGET<br>            a = [TARGET := EXPR for VAR in ITERABLE]<br><br>- Translation::<br><br>    def g():<br>        TARGET = ...<br>        def f():<br>            nonlocal TARGET<br>            def genexpr(iterator):<br>                nonlocal TARGET<br>                for VAR in iterator:<br>                    TARGET = EXPR<br>                    yield TARGET<br>            a = list(genexpr(iter(ITERABLE)))<br><br>Finally, let's nest two comprehensions.<br><br>- Original code::<br><br>    def f():<br>        a = [[TARGET := i for i in range(3)] for j in range(2)]<br>        # I.e., a = [[0, 1, 2], [0, 1, 2]]<br>        print(TARGET)  # prints 2<br><br>- Translation::<br><br>    def f():<br>        if False:<br>            TARGET = None<br>        def outer_genexpr(outer_iterator):<br>            nonlocal TARGET<br>            def inner_generator(inner_<wbr>iterator):<br>                nonlocal TARGET<br>                for i in inner_iterator:<br>                    TARGET = i<br>                    yield i<br>            for j in outer_iterator:<br>                yield list(inner_generator(range(3))<wbr>)<br>        a = list(outer_genexpr(range(2)))<br>        print(TARGET)<br><br><br>Appendix C: No Changes to Scope Semantics<br>==============================<wbr>===========<br><br>Because it has been a point of confusion, note that nothing about Python's<br>scoping semantics is changed.  Function-local scopes continue to be resolved<br>at compile time, and to have indefinite temporal extent at run time ("full<br>closures").  Example::<br><br>    a = 42<br>    def f():<br>        # `a` is local to `f`<br>        yield ((a := i) for i in range(3))<br>        yield lambda: a + 100<br>        print("done")<br><br>Then::<br><br>    >>> results = list(f()) # [genexp, lambda]<br>    done<br>    # The execution frame for f no longer exists in CPython,<br>    # but f's locals live so long as they can still be referenced.<br>    >>> list(map(type, results))<br>    [<class 'generator'>, <class 'function'>]<br>    >>> list(results[0])<br>    [0, 1, 2]<br>    >>> results[1]()<br>    102<br>    >>> a<br>    42<br><br><br>References<br>==========<br><br>.. [1] Proof of concept / reference implementation<br>   (<a href="https://github.com/Rosuav/cpython/tree/assignment-expressions" target="_blank">https://github.com/Rosuav/<wbr>cpython/tree/assignment-<wbr>expressions</a>)<br>.. [2] Pivotal post regarding inline assignment semantics<br>   (<a href="https://mail.python.org/pipermail/python-ideas/2018-March/049409.html" target="_blank">https://mail.python.org/<wbr>pipermail/python-ideas/2018-<wbr>March/049409.html</a>)<br><br><br>Copyright<br>=========<br><br>This document has been placed in the public domain.<br><br><br> <br>..<br>   Local Variables:<br>   mode: indented-text<br>   indent-tabs-mode: nil<br>   sentence-end-double-space: t<br>   fill-column: 70<br>   coding: utf-8<br>   End:<br><br></div></div></div><div><div dir="ltr"><div><div><br>-- <br><div dir="ltr" class="m_2578707701783894258m_5612156664810263641gmail-m_7784590023965289177gmail_signature">--Guido van Rossum (<a href="http://python.org/~guido" target="_blank">python.org/~guido</a>)</div></div></div></div></div>
</div>