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

Nicholas T ntung at ntung.com
Fri Apr 18 10:10:47 CEST 2008


Amaury - I think it's generally cleaner code to write
    for myObject in someList:
       if myObject.fits():
           process(myObject)
           break
than
   for myObject in someList:
      if myObject.fits():
         break
   process(myObject)

I see from csv.py how it could simplify things (e.g. if the else case was
less trivial); however, for csv.py specifically, lines 372 to 392 could
prob. be rewritten as

# default to length of string
thisType = len(row[col])
for typeFunc in [int, float, complex]:
    try:
        typeFunc(row[col])
        thisType = typeFunc
        break
    except (ValueError, OverflowError):
        pass

if columnTypes[col] is None:
    # add new column type
    columnTypes[col] = thisType
elif thisType != columnTypes[col]:
    # type is inconsistent, remove column from consideration
    del columnTypes[col]

I'd be interested in seeing how often it is actually used.

I suppose carrying loop variable after the loop makes some sense in the
context of having only local and global scopes: clearly one wouldn't want to
make code inside the loop use "global" to access variables outside of the
loop. Creating a special scope for loop iteration variables would probably
also be a bad thing, though py3k currently prints a warning about concurrent
modification; perhaps this is not so different.

Guido - sorry I didn't know. Given how scopes work in python, I don't think
this is going to go anywhere, so at the moment I'm not going to repost /
revive arguments.

Thanks,
Nicholas
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/python-3000/attachments/20080418/826f6208/attachment.htm 


More information about the Python-3000 mailing list