1

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).

2
  • 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. Commented May 13 at 0:12
  • yup, that does it. Somehow I just couldn't get there. Thanks!
    – MikeP
    Commented May 13 at 0:16

1 Answer 1

0

To find out the name of an attribute in a namedtuple from inside a method, you can use the _fields attribute that comes with every namedtuple. It's a tuple that lists all the attribute names. So, if you have the index of the attribute, you can get its name straight from _fields. If you're working with the attribute itself, just find its index in _fields and then you'll have the name.

It's a straightforward way to keep track of your attributes by name, even from within a method too.

Not the answer you're looking for? Browse other questions tagged or ask your own question.