[Python-ideas] PEP 572: Statement-Local Name Bindings

Chris Angelico rosuav at gmail.com
Wed Feb 28 00:29:29 EST 2018


On Wed, Feb 28, 2018 at 3:38 PM, Rob Cliffe via Python-ideas
<python-ideas at python.org> wrote:
>
> Hm, apologies.  This is in complete contrast to my previous post, where I
> was pretty enthusiastic about Chris's PEP.  But I can't resist sharing these
> thoughts ...
>
> There was some vague uneasiness at the back of my mind, which I think I have
> finally pinned down.  Consider Chris's example:
>          # Using a statement-local name
>         stuff = [[(f(x) as y), y] for x in range(5)]
> I think what bothered me was the asymmetry between the two uses of the
> calculated value of f(x).  It is not obvious at first glance that
>     [(f(x) as y), y]
> defines a 2-element list where the 2 elements are the same.

Hmm, very good point. In non-toy examples, I suspect this will be
somewhat overshadowed by the actual work being done, but this is
definitely a bit weird.

> Contrast
> something like (exact syntax bike-sheddable)
>           stuff = [ (with f(x) as y: [y,y])  for x in range(5)]
> or
>             stuff = [ (y,y] with f(x) as y) for x in range(5)]
> This also has the advantage (if it is? I think probably it is) that the
> scope of the temporary variable ("y" here) can be limited to inside the
> parentheses of the "with" sub-expression.

True, but it's also extremely wordy. Your two proposed syntaxes, if I
have this correct, are:

1) '(' 'with' EXPR 'as' NAME ':' EXPR ')'
2) '(' EXPR 'with' EXPR 'as' NAME ')'

Of the two, I prefer the first, as the second has the same problem as
the if/else expression: execution is middle-first. It also offers only
a slight advantage (in a comprehension) over just slapping another
'for' clause at the end of the expression. The first one is most
comparable to the lambda helper example, and is (IMO) still very
wordy. Perhaps it can be added in a section of "alternative syntax
forms"?

> And that it is not dependent on Python's evaluation order.
> Ir gives the programmer explicit control over the scope, which might
> conceivably be an advantage in more complicated expressions.

That shouldn't normally be an issue (execution order is usually pretty
intuitive), but if there are weird enough edge cases found in my
current proposal, I'm happy to mention this as a possible solution to
them.

ChrisA


More information about the Python-ideas mailing list