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

Ethan Furman ethan at stoneleaf.us
Fri Mar 2 12:51:19 EST 2018


On 03/02/2018 02:47 AM, Nick Coghlan wrote:
> On 2 March 2018 at 16:39, Ethan Furman wrote:
>> On 03/01/2018 09:08 PM, Nick Coghlan wrote:

>>> Adding statement local variables into that mix *without* some form of syntactic marker would mean taking an already
>>> complicated system, and making it even harder to reason about correctly (especially if statement locals interact
>>> with nested scopes differently from the way other locals in the same scope do).
>>
>> Seems like it would far easier and (IMHO) more useful to scale the proposal back from a statement scope to simple
>> expression assignment, and the variable is whatever scope it would have been if assigned to outside the expression
>> (default being local, but non-local or global if already declared as such).
>
> Because that would put us back in the exact same problematic situation we had when "[x*x for x in sequence]" leaked the
> iteration variable (only worse): no function locals would be safe, since arbitrary expressions could clobber them, not
> just name binding operations (assignment, import statements, for loops, with statements, exception handlers, class and
> function definitions).

Ah, right.  Since the PEP primarily covers comprehensions, but then went on to discuss multi-line statements, I had 
forgotten the comprehension part.  The answer is easy:  assignment expressions in comprehensions stay inside 
comprehensions, just like other inner comprehension variables already do (function sub-scope, after all).  Thank you for 
pointing that out.

>> Maybe somebody could explain why a statement-local limited scope variable is better than an ordinary well-understood
>> local-scope variable?  Particularly why it's better enough to justify more line-noise in the syntax.  I'm willing to
>> be convinced (not happy to, just willing ;) .
>
> It breaks the expectation that only a well defined subset of statement can make changes to local name bindings.

We already use the keyword "as" to assign names, so there is nothing extra there -- the only change is that we can now 
use it in one more place.

Are those valid counter-arguments, or is there still something I am missing?

--
~Ethan~


More information about the Python-ideas mailing list