Loop Variables Overwrite Globals

对着背影说爱祢 提交于 2021-01-28 11:56:16

问题


In python, why do loop variables overwrite already defined global variables? It seems counterintuitive that a loop variable is put into the module's global namespace rather than a new local namespace just for the loop. Here's an example that shows what I'm talking about:

c = 3.14

print("before loop c = {}".format(c))
for c in range(3):
    print("in loop c = {}".format(c))
print("after loop c = {}".format(c))

Running this code will print out:

before loop c = 3.14
in loop c = 0
in loop c = 1
in loop c = 2
after loop c = 2

Reusing names like this is almost definitely bad coding style, but it may happen accidentally in large modules and cause globals to be defined where you don't expect them to be. For example if I were to do this:

def f(x):
     print("x is {}".format(c)) # finger slipped, wrote c instead of x

for c in range(3):
    print("c is {}".format(c))

for a in "test":
    f(a)

I would get:

c is 0
c is 1
c is 2
x is 2
x is 2
x is 2
x is 2

This question seems to indicate that for loops don't have their own namespace by design. What is the rationale behind this when it can cause bugs depending on when loops are run relative to the execution order of the program?

来源:https://stackoverflow.com/questions/31544391/loop-variables-overwrite-globals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!