[Python-Dev] assignment expressions: an alternative proposal

Yury Selivanov yselivanov.ml at gmail.com
Tue Apr 24 11:25:58 EDT 2018


On Tue, Apr 24, 2018 at 11:15 AM, Steven D'Aprano <steve at pearwood.info> wrote:
[..]

>> >> 3. Most importantly: it is *not* allowed to mask names in the current
>> >> local scope.
>
> That means you can't rebind existing variables. That means you can't
> rebind to the same variable in a loop.

No, it doesn't. The check is performed during compile phase, and
Python does not unroll loops. Anyways, read below.

> I believe that one of the most important use-cases for binding-
> expression syntax is while loops, like this modified example taken from
> PEP 572 version 3:
>
>     while (data = sock.read()):
>         print("Received data:", data)
>
> If you prohibit re-binding data, that prohibits cases like this, or even
> using it inside a loop:
>
>     for value in sequence:
>         process(arg, (item = expression), item+1)

No it doesn't. symtable in Python works differently. I encourage you
to test my reference implementation:

py> for val in [1, 2, 3]:
...   print((item=val), item+1)
...
1 2
2 3
3 4

> Why is this allowed?
>
>     x = 1  # both are statement forms
>     x = 2
>
> but this is prohibited?
>
>     x = 1
>     (x = 2)  # no rebinding is allowed
>
> and even more confusing, this is allowed!
>
>     (x = 1)  # x doesn't exist yet, so it is allowed
>     x = 2  # statement assignment is allowed to rebind

These all are very limited code snippets that you're unlikely to see
in real code.  I can write (and I did in this thread) a bunch of
examples of where PEP 572 is also inconsistent.

Yury


More information about the Python-Dev mailing list