[Python-ideas] If branch merging

Ron Adam ron3200 at gmail.com
Fri Jun 12 20:25:20 CEST 2015



On 06/12/2015 01:21 PM, Ethan Furman wrote:
> On 06/12/2015 08:14 AM, Stephen J. Turnbull wrote:
>> Ethan Furman writes:
>>
>>> Likewise:
>>>
>>>     for val in some_iterator:
>>>        use(val)
>>>
>>>     bar(val)
>>>
>>> will shadow foo.val
>>
>> Yes, I understand that.  What I don't understand is your statement
>> that you would like "if expr as val:" if it *doesn't* shadow.
>
> Ah, I think I see your point.  My use of the word "shadow" was in relation
> to the micro-scope and the previously existing name being shadowed and then
> un-shadowed when the micro-scope was destroyed. If we are at module-level
> (not class nor function) then there should be no shadowing, but a rebinding
> of the name.  Even try/except blocks don't "shadow", but rebind and then
> delete the name used to catch the exception.

The problem can be turned around/over.  Instead of specifying a name to be 
shadowed, the names to be shared can be specified.  Then it translates to 
function with specified nonlocals.


     a = 1             # will be shared
     b = 2             # will be shadowed

     def do_loop_with_shared_items():
         nonlocal a                      # a is a shared value.
         for b in some_iterator:
             a = use(b)
     do_loop_with_shared_items()

     print(a)     # changed by loop
     print(b)     # print 2. Not changed by loop


That might be expressed as...

     a = 1
     b = 2

     with nonlocal a:                 # a is shared
         for b in some_iterator:
             a = use(b)               # other values (b) are local to block.

     print(a)     # changed by loop
     print(b)     # prints 2. Not changed by loop


And with this, the "as" modifier isn't needed, just don't list the item as 
a nonlocal.

     with nonlocal:
         a = foo.bar          # a as foo.bar in this block scope only.
         ,,,

This has the advantage of not complicating other statements and keeps the 
concept in a separate mental box.

I like this better, but am still -0.5.  I'd need to see some examples where 
it would be "worth it".  It still feels like a solution looking for a 
problem to me.


Cheers,
    Ron



More information about the Python-ideas mailing list