Namedtuples: some unexpected inconveniences

Deborah Swanson python at deborahswanson.net
Wed Apr 12 20:04:30 EDT 2017


Deborah Swanson wrote, on Wednesday, April 12, 2017 4:29 PM
> 
> Peter Otten wrote, on Wednesday, April 12, 2017 3:15 PM
> > 
> > >> Indeed you cannot change the namedtuple's attributes. Like the
> > >> "normal" tuple it is designed to be immutable. If you want
changes in 
> > >> one list (the group) to appear in another (the original records)
you 
> > >> need a mutable data type.
> > > 
> > > Sadly, that does seem to be the correct conclusion here.
> > 
> > Think hard if you really need the original list.
> 
> It's possible you might transform the namedtuple into a 
> mutable type, and I didn't try that. But it seems like the 
> group-by defaultdict strategy would have to have a 
> significant performance edge to be worth it and you wouldn't 
> have any of the namedtuple properties to work with after the 
> transformation. I also ran into some trouble with your 
> algorithm that follows making the defaultdict, and I'm not 
> sure what value there would be in hashing through that. 
> Though I'm certainly willing to if you are.
> 
> It worked to simply stay with the original list of 
> namedtuples to begin with.
> 
> I remain grateful for your introduction to the collections 
> module. What a neat little package of tools!

I know it's quick for this double-take, but it occurs to me that
transforming to a mutable type isn't a performance evaluation at all.
Filling in missing values is the last step before outputting the
processed list, so it might not be necessary to work with namedtuples at
that point.

The algorithm to fill in the missing values for each group (which would
no longer be namedtuples) in the defaultdict is something I'm back at
the drawing board for. But it shouldn't be too hard. Haha, we'll see!



More information about the Python-list mailing list