Why are arbitrary target expressions allowed in for-loops?

后端 未结 4 1441
臣服心动
臣服心动 2020-12-12 20:14

I accidentally wrote some code like this:

foo = [42]
k = {\'c\': \'d\'}

for k[\'z\'] in foo:  # Huh??
    print k

But to my surprise, this

4条回答
  •  甜味超标
    2020-12-12 21:13

    Every name is just a dictionary key*.

    for x in blah:
    

    is precisely

    for vars()['x'] in blah:
    

    * (though that dictionary needn't be implemented as an actual dict object, in case of some optimizations, such as in function scopes).

提交回复
热议问题