unintuitive for-loop behavior

Steve D'Aprano steve+python at pearwood.info
Fri Sep 30 08:33:54 EDT 2016


On Fri, 30 Sep 2016 05:29 am, namenobodywants at gmail.com wrote:

> hello pythonistas
> 
> 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; 

Giving for-loops their own namespace is a grossly unintuitive and a very
weird thing to do. Modules, classes and functions are obviously namespaces.
Why should arbitrary syntactic structures create their own namespace?

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


unless you declared it nonlocal or global, depending on whether your for
loop was inside a function or not.

To me, "make for-loops be their own scope" sounds like a joke feature out of
joke languages like INTERCAL. I'm not aware of any sensible language that
does anything like this.

No, wait a minute, I tell a lie, I recall Chris Angelico mentioning that one
of his favourite languages, Pike or REXX, does it. I forget which.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list