Namedtuples problem

Deborah Swanson python at deborahswanson.net
Fri Feb 24 00:27:40 EST 2017


Gregory Ewing wrote, on February 23, 2017 9:07 PM
> 
> Deborah Swanson wrote:
> > I've run into this kind of problem with namedtuples before, 
> trying to 
> > access field values with variable names, like:
> > 
> > label = 'Location'
> > records.label
> 
> If you need to access an attribute whose name is computed
> at run time, you want getattr() and setattr():
> 
>     value = getattr(record, label)
> 
>     setattr(record, label, value)
> 
> Using these, I suspect you'll be able to eliminate all
> the stuff you've got that messes around with indexes to
> access field values, making the code a lot simpler and
> easier to follow.
> 
> -- 
> Greg

Steve D'Aprano mentioned using getattr(record, label) and I thought that
might be the way to untangle a lot of the mess I made. Been futzing
around with different ways to use it, but I'll look at setattr(record,
label, value) first thing in the morning. 

Thanks bunches!

Deborah




More information about the Python-list mailing list