Namedtuples: some unexpected inconveniences

Deborah Swanson python at deborahswanson.net
Thu Apr 13 20:52:15 EDT 2017


Gregory Ewing wrote, on Thursday, April 13, 2017 12:34 AM
> 
> 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

That's good advice and I'll rewrite it that way, after I have the code I
started with to answer the other questions.

I certainly know I have a lot to learn about writing good code, and I
can see that what you're suggesting is much cleaner than what I had.

Thanks,
Deborah




More information about the Python-list mailing list