19
votes

Is the following code bad practice?

for i in some_values:
    do_whatever(i)
do_more_things(i)

Somehow, it feels to me like the variable i should remain in the scope to the block inside the for-loop. However python 2.7 lets me reuse it after the loop.

Does python officially supports that feature, or am I abusing the language?

5
hmmm... seems like this might be ok since it is used here - jamylak
There are a fair number of use-cases which benefit from accessing the last value of a loop variable in subsequent code - This

5 Answers

16
votes

Yes, it's official:

for_stmt ::=  "for" target_list "in" expression_list ":" suite
              ["else" ":" suite]

> The target list is not deleted when the loop is finished 

http://docs.python.org/reference/compound_stmts.html#for

Note that a target list after for is far more than just a variable:

for some_list[blah] in...
for some_object.foo in...
for a[:n] in ...:

etc. These things cannot simply disappear after the loop.

6
votes

Python can feel a bit special when it comes to scoping if you are coming from languages like C or Java. As previous answer says, the code is absolutely valid but I would recommend against it. It creates not particularly readable code and, furthermore, if some_values turns out to be empty, there will be an exception raised on the last line of the code.

So answer to your question is - yes, it is officially supported but in most cases it is not recommended strategy.

Interesting discussion can be found here and also local discussion on SO.

5
votes

You can use this technique to scan a list for items matching some criteria:

for item in iter:
    if interesting(item):
        break
else:
    raise ValueError('iter is boring.')

handle(item)
1
votes

Just like @petr said, it sound unnatural. Not because it's allowed that it's natural or you have to use it.

I rather have something like this, although it may not apply to the logic with a break use-case:

for i in some_values:
    do_whatever(i)
else:
    do_more_things(i)

But this still raise NameError if some_values evaluate to empty, but sounds clearer. It does not give the clear readability of an inner scope but the indentation may suggests it.

But as other said, to answer to the specific OP's question, yes, it's legal.

-1
votes

That's not a feature. As you wrote the variable remains in the scope. It's normal interpreter behavior.