There must be a better way

Colin J. Williams cjw at ncf.ca
Sun Apr 21 09:15:28 EDT 2013


On 20/04/2013 9:07 PM, Terry Jan Reedy wrote:
> On 4/20/2013 8:34 PM, Tim Chase wrote:
>> In 2.x, the csv.reader() class (and csv.DictReader() class) offered
>> a .next() method that is absent in 3.x
>
> In Py 3, .next was renamed to .__next__ for *all* iterators. The
> intention is that one iterate with for item in iterable or use builtin
> functions iter() and next().
>
>
Thanks to Chris, Tim and Terry for their helpful comments.

I was seeking some code that would be acceptable to both Python 2.7 and 3.3.

In the end, I used:

inData= csv.reader(inFile)

def main():
     if ver == '2':
         headerLine= inData.next()
     else:
         headerLine= inData.__next__()
     ...
     for item in inData:
         assert len(dataStore) == len(item)
         j= findCardinal(item[10])
         ...

This is acceptable to both versions.

It is not usual to have a name with preceding and following 
udserscores,imn user code.

Presumably, there is a rationale for the change from csv.reader.next
to csv.reader.__next__.

If next is not acceptable for the version 3 csv.reader, perhaps __next__ 
could be added to the version 2 csv.reader, so that the same code can be 
used in the two versions.

This would avoid the kluge I used above.

Colin W.




More information about the Python-list mailing list