Scoping in Python 'for' loops

前端 未结 6 1187
名媛妹妹
名媛妹妹 2020-11-22 03:52

I\'m not asking about Python\'s scoping rules; I understand generally how scoping works in Python for loops. My question is why the design decisions were m

6条回答
  •  盖世英雄少女心
    2020-11-22 04:32

    The likeliest answer is that it just keeps the grammar simple, hasn't been a stumbling block for adoption, and many have been happy with not having to disambiguate the scope to which a name belongs when assigning to it within a loop construct. Variables are not declared within a scope, it is implied by the location of assignment statements. The global keyword exists just for this reason (to signify that assignment is done at a global scope).

    Update

    Here's a good discussion on the topic: http://mail.python.org/pipermail/python-ideas/2008-October/002109.html

    Previous proposals to make for-loop variables local to the loop have stumbled on the problem of existing code that relies on the loop variable keeping its value after exiting the loop, and it seems that this is regarded as a desirable feature.

    In short, you can probably blame it on the Python community :P

提交回复
热议问题