Namedtuples: some unexpected inconveniences
Deborah Swanson
python at deborahswanson.net
Thu Apr 13 21:01:49 EDT 2017
Gregory Ewing wrote, on Thursday, April 13, 2017 1:14 AM
>
> Deborah Swanson wrote:
> > I don't exactly understand your point (2). If the
> namedtuple does not
> > have a label attribute, then getattr(record, label) will
> get the error
> > whether the name label holds the string 'label' or not.
>
> You sound rather confused. Maybe the following interactive
> session transcript will help.
>
> >>> from collections import namedtuple
> >>> record = namedtuple('record', 'alpha,beta')
> >>> r = record(1, 2)
> >>> r
> record(alpha=1, beta=2)
> >>> label = 'alpha'
> >>> getattr(r, label)
> 1
> >>> label = 'beta'
> >>> getattr(r, label)
> 2
> >>> label = 'gamma'
> >>> getattr(r, label)
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> AttributeError: 'record' object has no attribute 'gamma'
>
> Can you see what's happening here? The expression
>
> label
>
> is being evaluated, and whatever string it evaluates to is
> being used as the attribute name to look up.
>
> Now, I'm not sure exactly what you were doing to get the
> message "'record' object has no attribute 'label'". Here are
> a few possible ways to get that effect:
>
> >>> r.label
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> AttributeError: 'record' object has no attribute 'label'
>
> >>> getattr(r, 'label')
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> AttributeError: 'record' object has no attribute 'label'
>
> >>> label = 'label'
> >>> getattr(r, label)
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> AttributeError: 'record' object has no attribute 'label'
>
> Or maybe you did something else again. We would need to
> see your code in order to tell.
>
> --
> Greg
And it's reproducing the code that's the roadblock to all of these
issues.
Rest assured I will get to the bottom of this, or at least come back
with the code to ask more questions about it and let you see what I had.
I want to see what's going on here too.
Might be a day or two though.
Deborah
More information about the Python-list
mailing list