unintuitive for-loop behavior

namenobodywants at gmail.com namenobodywants at gmail.com
Thu Sep 29 15:29:05 EDT 2016


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; now i'm reading up on the language and i find out that's not the case: the loop variable gets put into the enclosing namespace, overwriting any former value that was already there; of course i realize there are situations where one is interested in the value that a loop variable has after the loop has been exited, but this behavior seems grossly unintuitive to me: has there ever been any discussion of giving for-loops the option of running in namespaces of their own? 

and it gets even worse; consider the following means of raising an exception:

#)-------------------------------------- begin code

def powerfunction(exponent): 
    return lambda base: (base ** exponent)

p1 = [powerfunction(exponent)         for exponent in range(9)]
p2 = [lambda base: (base ** exponent) for exponent in range(9)]

assert p1[3](4) == p2[3](4)

#)---------------------------------------- end code

apparently the problem is that "exponent" gets evaluated when the relevant lambda function is run, not when it's defined, but no binding for "exponent" gets put into the enclosing namespace: it seems that python remembers this ghostly "exponent" for me on the theory that i don't WANT "p1" and "p2" to be the same; can anyone help to reconcile me to this semantics?

thanks if you can help
stm












More information about the Python-list mailing list