[Python-ideas] Where-statement (Proposal for function expressions)

MRAB python at mrabarnett.plus.com
Fri Jul 17 15:06:14 CEST 2009


Mike Meyer wrote:
> On Fri, 17 Jul 2009 14:02:34 +1200
> Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> 
>> Daniel Stutzbach wrote:
>>
>>> If the
>>> left-hand side were in the where-block's scope, then:
>>>
>>> x = 0
>>> x = i where:
>>>    i = 5
>>> print x
>>>
>>> Would print "0" not "5".
>> My intuitive expectations are different for assignment
>> to a bare name vs. assignment to an item or attribute.
>> In
>>
>>    x = i where:
>>      i = 5
>>
>> I would expect x to be bound in the current scope,
>> not the where-block scope. But I would expect
>>
>>    x[i] = 5 where:
>>      x = y
>>      i = 7
>>
>> to be equivalent to
>>
>>    y[7] = 5
>>
>> i.e. both x and i are *evaluated* in the where-block
>> scope.
>>
>> I'm not sure where this leaves us with respect to
>> augmented assignment, though. If you follow it to
>> its logical conclusion, then
>>
>>    x += i where:
>>      i = 5
>>
>> should be equivalent to
>>
>>    x = x.__iadd__(i) where:
>>      i = 5
>>
>> and then the evaluation and rebinding of 'x' would
>> happen in different scopes!
> 
> That evaluating an expression to the right of an augmented assignment
> might return something different than what you would bind that
> expression to has always been an issue with augmented assignments. I
> believe this particular problem belongs has more to do with them than
> with the proposed where statement.
> 
> I think the intuitive behavior doesn't involve position relative to
> the assignment, but binding vs. non-bindings. What you *expect* is
> that expressions left of the where will be evaluated in the inner
> scope (created by the where), but that any bindings that happen there
> will happen in the outer scope (before the where).
> 
> That makes what you want to happen happen - *most* of the time:
> 
> i = 3
> x += i where:
>    i = 5
> 
> increments x by 5.
> 
> i = 'a'
> x[i] = 'b' where:
>    i = 'c'
> 
> sets x['c'] to 'b'.
> 
> Things get really ugly when the bound variables start appearing in
> both scopes combined with augmented assignments:
> 
> x = 3
> x += 4 where:
>     x = 5
> print x
> 
> What should this print?
> 
The target line assigns to x, therefore x is not local. It should print 9.

x = 3
local:
     nonlocal x
     x = 5
     x += 4 # The target line.



More information about the Python-ideas mailing list