unintuitive for-loop behavior

BartC bc at freeuk.com
Fri Sep 30 09:43:25 EDT 2016


On 30/09/2016 13:33, Steve D'Aprano wrote:
> On Fri, 30 Sep 2016 05:29 am, namenobodywants at gmail.com wrote:

>> i've had a nodding acquaintance with python for some time, and all along i
>> assumed that for-loops got a namespace of their own;

> It would be terribly inconvenient and surprising for if...else blocks to be
> separate namespaces:
>
> a = 1
> if condition:
>     print(a)  # UnboundLocalError: local 'a' referenced before assignment
>     a += 1
>
>
> For-loops are no different. Making them their own namespace is a very
> strange thing to do, it would mean you couldn't re-bind a value inside a
> for-loop:
>
> count = 0
> for x in sequence:
>     count += 1
>     # raises UnboundLocalError: local 'count' referenced before assignment

It can make sense for 'x' to be local to this for-loop block (everything 
else is at it works now), and independent of any x's in outer blocks. It 
means being able to do stuff like this:

    for x in a:
      for x in b:
         pass
      pass     # outer x still has its value

And any even more outer x's are not affected. With 'for', especially one 
inside a list-comp, often you just need some throwaway index variable 
without worrying if it will clash with an existing local.

But it's not useful enough I think to bother changing now. Or even when 
the language was designed.

-- 
Bartc




More information about the Python-list mailing list