[Python-ideas] PEP 572: Statement-Local Name Bindings
rosuav at gmail.com
Thu Mar 1 01:40:51 EST 2018
On Thu, Mar 1, 2018 at 3:31 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> On 28 February 2018 at 08:27, Chris Angelico <rosuav at gmail.com> wrote:
>> 2. The current implementation  implements statement-local names using
>> a special (and mostly-invisible) name mangling. This works perfectly
>> inside functions (including list comprehensions), but not at top
>> level. Is this a serious limitation? Is it confusing?
> It isn't clear to me from the current PEP what the intended lifecycle of the
> bound names actually is, especially for compound statements.
I think you're looking at an old version of the PEP, but that's kinda
gonna happen on the first day of a hot topic :) But to remove all
confusion, I've now added a section clarifying execution order, using
several of your examples.
> x = (expr as y)
> assert x == y # Does this pass? Or raise NameError for 'y'?
NameError. The SLNB is gone at end of line.
> if (condition as c):
> assert c # Does this pass? Or raise NameError for 'c'?
> assert not c # Does this pass? Or raise NameError for 'c'?
> assert c or not c # Does this pass? Or raise NameError for 'c'?
c is available in the indented blocks, and is gone once the entire
'if/else' block is done.
> class C:
> x = (True as y)
> assert C.y # Does this pass? Or raise AttributeError for 'y'?
That'll raise. (At least, according to the specification and intent.
The reference implementation may be lagging a bit.)
> I think it would also be worth explicitly considering a syntactic variant
> that requires statement local references to be explicitly disambiguated from
> regular variable names by way of a leading dot:
> result = [[(f(x) as .y), .y] for x in range(5)]
> Since ".NAME" is illegal for both variable and attribute names, this makes
> the fact statement locals are a distinct namespace visible to readers as
> well as to the compiler, and also reduces the syntactic ambiguity in with
> statements and exception handlers.
I've mentioned this in the alternate syntaxes, but I don't like having
to state a variable's scope in its name. Python doesn't force us to
adorn all global names with a character, and the difference between
function-local and statement-local is generally less important than
the difference between global and function-local. But it IS a viable
syntax, and I'm saying so in the PEP.
Thanks for the feedback! Much appreciated.
More information about the Python-ideas