[Python-Dev] PEP 572: Assignment Expressions

Nick Coghlan ncoghlan at gmail.com
Sun Apr 22 01:33:26 EDT 2018


On 22 April 2018 at 02:31, Steven D'Aprano <steve at pearwood.info> wrote:
> This is not entirely unprecedented in Python: it is analogous
> (although not identical) to binding default values to parameters:
>
>     def running_total(items, total=total):
>         # Here total is local to the function, but the default
>         # is taken from the surrounding scope.

The stronger precedent for "look up elsewhere until first use" is class scopes:

    >>> x = "global"
    >>> class C:
    ...     print(x)
    ...     x = "class attribute to be"
    ...     print(x)
    ...
    global
    class attribute to be

However, that has its own quirks, in that it ignores function scopes entirely:

    >>> def f():
    ...     x = "function local"
    ...     class C:
    ...         print(x)
    ...         x = "class attribute to be"
    ...         print(x)
    ...
    >>> f()
    global
    class attribute to be

Whereas if you don't rebind the name in the class body, the class
scope can see the function local as you'd expect:

    >>> def f2():
    ...     x = "function local"
    ...     class C:
    ...         print(x)
    ...
    >>> f2()
    function local

While I haven't explicitly researched the full history, my assumption
is that references from class scopes prior to a local name rebinding
are an edge case that https://www.python.org/dev/peps/pep-0227/ didn't
fully account for, so they retain their original pre-PEP-227
behaviour.

Cheers,
Nick.

P.S. It may be becoming clearer why the earlier iterations of PEP 572
proposed sublocal scoping semantics for the new name binding
expression: it not only gives greater differentiation from traditional
assignments and limits the potential for obviously unwanted side
effects like accidentally clobbering a name that's already in use, it
also sidesteps a lot of these quirky name resolution issues that arise
when you use full local name bindings.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-Dev mailing list