[Python-Dev] elimination of scope bleeding of iteration variables
Nick Coghlan
ncoghlan at gmail.com
Sun Apr 30 16:23:54 CEST 2006
Ben Wing wrote:
> apologies if this has been brought up on python-dev already.
>
> a suggestion i have, perhaps for python 3.0 since it may break some code
> (but imo it could go into 2.6 or 2.7 because the likely breakage would
> be very small, see below), is the elimination of the misfeature whereby
> the iteration variable used in for-loops, list comprehensions, etc.
> bleeds out into the surrounding scope.
>
> [i'm aware that there is a similar proposal for python 3.0 for list
> comprehensions specifically, but that's not enough.]
List comprehensions will be fixed in Py3k. However, the scoping of for loop
variables won't change, as the current behaviour is essential for search loops
that use a break statement to terminate the loop when the item is found.
Accordingly, there is plenty of code in the wild that *would* break if the for
loop variables were constrained to the for loop, even if your own code
wouldn't have such a problem.
Outside pure scripts, significant control flow logic (like for loops) should
be avoided at module level. You are typically much better off moving the logic
inside a _main() function and invoking it at the end of the module. This
avoids the 'accidental global' problem for all of the script-only variables,
not only the ones that happen to be used as for loop variables.
> # Replace property named PROP with NEW in PROPLIST, a list of tuples.
> def property_name_replace(prop, new, proplist):
> for i in xrange(len(proplist)):
> if x[i][0] == prop:
> x[i] = (new, x[i][1])
This wouldn't have helped with your name-change problem, but you've got a lot
of unnecessary indexing going on there:
def property_name_replace(prop, new, proplist):
for i, (name, value) in enumerate(proplist):
if name == prop:
proplist[i] = (new, value)
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
http://www.boredomandlaziness.org
More information about the Python-Dev
mailing list