Namedtuples problem

Steve D'Aprano steve+python at pearwood.info
Thu Feb 23 09:11:07 EST 2017


On Thu, 23 Feb 2017 08:38 pm, Deborah Swanson wrote:

> However,
> 
> group[[idx][records_idx[label]]]
> gets an Index Error: list index out of range

That's not very helpful: judging from that line alone, there could be as
many as THREE places in that line of code that might generate IndexError.

When you have code complex enough that you can't understand the error it
gives, break it up into separate steps:

# group[[idx][records_idx[label]]]
i = records_idx[label]
j = [idx][i]
group[j]

Now at least you will find out which step is failing!

Since records_idx is a dict, if that fails it should give KeyError, not
IndexError. So it won't be that line, at least not if my reading of your
code is correct.

The most likely suspect is the second indexing operation, which looks mighty
suspicious:

    [idx][i]


What a strange thing to do: you create a list with a single item, idx, and
then index into that list with some value i. Either i is 0, in which case
you get idx, or else you get an error.

So effectively, you are looking up:

    group[idx]

or failing.



> I've run into this kind of problem with namedtuples before,

This is nothing to do with namedtuples. You happen to be using namedtuples
elsewhere in the code, but that's not what is failing. namedtuple is just
an innocent bystander.


> trying to 
> access field values with variable names, like:
> 
> label = 'Location'
> records.label
> 
> and I get something like "'records' has no attribute 'label'.

Which has nothing to do with this error.

When the attribute name is known only in a variable, the simplest way to
look it up is:

    getattr(records, label)




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list