This is a followup to How can I pass a namedtuple attribute to a method without using a string?. Given this solution to the above:
from typing import NamedTuple
class Record(NamedTuple):
id: int
name: str
age: int
class NamedTupleList:
def __init__(self, data):
self._data = data
def attempt_access(self, row, column):
r = self._data[row]
try:
val = r[column]
except TypeError:
val = column.__get__(r)
return val
data = [Record(1, 'Bob', 30),
Record(2, 'Carol', 25),
]
class_data = NamedTupleList(data)
print(class_data.attempt_access(0, 2)) # 30
print(class_data.attempt_access(0, Record.age)) # 30
My question is, is there a way to get the name of the attribute from inside the method? In other words, in this example how can I get 'age'
inside the method attempt_access
so I can produce a more useful error message (for other stuff not shown).
Record.age.__get__(Record._fields)
returns'age'
- basically, this uses the descriptor to grab an item from the_fields
tuple,. rather than the NamedTuple itself.