[Python-3000] end scope of iteration variables after loop

Amaury Forgeot d'Arc amauryfa at gmail.com
Thu Apr 17 10:48:18 CEST 2008


Nicholas T wrote:
> hello all,
>
>    A few times in practice I have been tripped up by how Python keeps
> variables in scope after a loop--and it wasn't immediately obvious what the
> problem was. I think it is one of the ugliest and non-intuitive features,
> and hope some others agree that it should be changed in py3k.
>
> >>> for a in range(11): pass
> ...
> >>> print(a)
> 10

There are use cases when the last value of the loop variable is needed
after a "break" statement.

    for myObject in someList:
        if myObject.fits():
            break
    else:
        myObject = someDefaultValue

     # continue with myObject

See for example in csv.py, function Sniffer.has_header() [*]:
The loop tries to find a suitable value for the "thisType" variable,
then use it.

I like to use this pattern: it avoids an additional variable with the
same meaning,
and still separates the search from the other processing.

[*] BTW, in the py3k version there are two obvious simplifications,
due to the long->int massive replace.
-- 
Amaury Forgeot d'Arc


More information about the Python-3000 mailing list