4 ms·
>> none of the code on this page is something anyone would actually write in production code on purpose. I mostly agree, but there is one example where I thoug
by singularity2001 6y ago
>> none of the code on this page is something anyone would actually write in production code on purpose.
I mostly agree, but there is one example where I thought it is important to know and remember:
for x in range(7):
def some_func():
return x
Here x binds to the (outside) symbol x, not the value of x at creation time of the inner function.
- pansa2 6y agoYes - in many languages x is a new variable on each iteration of the loop. Python re-uses the same variable each time, because the loop does not have its own scope.
- iovrthoughtthis 6y agoI’ve seen a number of experienced python programmers bitten by this. They expect a new scope but don’t get one.
- edflsafoiewq 6y agoThat's how I expect it to behave. But anyway, the alternative (x in a new lexical environment each time the loop body is entered) only makes sense in a language where variables are scoped to a lexical block, not in Python where variables are scoped to the whole function.