Safely using for-loop variables outside the loop
<p><a href="http://stackoverflow.com/a/3611987/336527">Most arguments</a> about why the design decision was made to make for-loop variables <em>not</em> local to the loop suggest that there are popular use cases.</p>

<p>The obvious use case is this:</p>

<pre><code>x = default_value
for x in iterator:
    # do stuff
# do something with x here
</code></pre>

<p>Unfortunately, often the first line is forgotten:</p>

<pre><code># should have set default value for x here
# but forgot
for x in iterator:
    # do stuff
# do something with x here
</code></pre>

<p>So when iterator is empty, they raise <code>NameError</code> if <code>x</code> was not defined earlier.</p>

<p>This mistake gets worse with nested loops:</p>

<pre><code>for y in outer_iterator:
    # should have set default value for x here
    # but forgot
    for x in inner_iterator(y):
        # do stuff
    # do something with x
</code></pre>

<p>Here forgetting the <code>x = default_value</code> results in a silent error instead of an exception if <code>inner_iterator(y)</code> is empty on the second or later iteration through the outer loop.</p>

<p>Testing these situations is tough, because <code>inner_iterator(y)</code> is not an outside argument, so unless the test is lucky enough to somehow recreate the case when it's empty, the bug won't be detected.</p>

<p>Are all use cases fragile or is there a safe way to rely on the scoping rule of the for-loop variables? </p>

<p>I agree that the most obvious reason for loops not to have their own scope, is the complications that would introduce when assigning values to variables in the outer scope.</p>

<p>But that does not necessarily mean the iterated value. Consider the following:</p>

<pre><code>total = 0
for item in some_list:
    total += item
</code></pre>

<p>If the loop had its own variable scope, implementing this would be a nightmare.</p>

<p>One of the onsequences is that the <code>item</code> is also avaialable out of the loop, but that does not really mean there is a nice way (or as you say <em>"safe"</em> way) to use it.</p>

<p>You can use it, but then you have to be careful.</p>

python python-3.x scope