[Python-ideas] PEP 572: Statement-Local Name Bindings, take three!

Steven D'Aprano steve at pearwood.info
Sun Apr 8 11:01:12 EDT 2018

On Sun, Apr 08, 2018 at 09:25:33PM +1000, Nick Coghlan wrote:

> I was writing a new stdlib test case today, and thinking about how I
> might structure it differently in a PEP 572 world, and realised that a
> situation the next version of the PEP should discuss is this one:
>     # Dict display
>     data = {
>         key_a: 1,
>         key_b: 2,
>         key_c: 3,
>     }
>     # Set display with local name bindings
>     data = {
>         local_a := 1,
>         local_b := 2,
>         local_c := 3,
>    }

I don't understand the point of these examples. Sure, I guess they would 
be legal, but unless you're actually going to use the name bindings, 
what's the point in defining them?

data = {
    (spam := complex_expression),

which I think is cleaner than the existing alternative of defining spam 
outside of the set.

And for dicts:

d = {
   'key': 'value',
   (spam := calculated_key): (eggs := calculated_value),
   spam.lower(): eggs.upper(),

> I don't think this is bad (although the interaction with dicts is a
> bit odd), and I don't think it counts as a rationale either, but I do
> think the fact that it becomes possible should be noted as an outcome
> arising from the "No sublocal scoping" semantics.

If we really wanted to keep the sublocal scoping, we could make 
list/set/dict displays their own scope too.

Personally, that's the only argument for sublocal scoping that I like 
yet: what happens inside a display should remain inside the display, and 
not leak out into the function.

So that has taken me from -1 on sublocal scoping to -0.5 if it applies 
to displays.


More information about the Python-ideas mailing list