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
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to