Namedtuples: some unexpected inconveniences

Gregory Ewing greg.ewing at canterbury.ac.nz
Thu Apr 13 03:34:27 EDT 2017


Deborah Swanson wrote:
> Peter Otten wrote, on Wednesday, April 12, 2017 1:45 PM
> 
>> Personally I would immediately discard the header row once and for
>> all, not again and again on every operation.
> 
> Well, perhaps, but I need the header row to stay in place to write the
> list to a csv when I'm done

That's no problem, just write the header row separately.

Do this at the beginning:

   header = [Record._make(fieldnames)]
   records = [Record._make(row) for row in rows]

and then to write out the file:

   writer = csv.writer(outputfile)
   writer.writerow(header)
   writer.writerows(records)

> There might be a tiny performance edge in discarding the header
> row for the sort, but there would also be a hit to recreate it at output
> time.

It's not about performance, it's about keeping the code as clean
and simple as you can, thus making it easier to understand and
maintain.

The general idea to take away from this is that it's almost always
best to arrange things so that a given collection contains just
one kind of data, so you can treat every element of it in exactly
the same way.

-- 
Greg


More information about the Python-list mailing list