Getting name of value from namedtuple

user278618 picture user278618 · Jul 4, 2011 · Viewed 41.7k times · Source

I have a module with collection:

import collections
named_tuple_sex = collections.namedtuple(
                    'FlightsResultsSorter',
                        ['TotalPriceASC',
                         'TransfersASC',
                         'FlightTimeASC',
                         'DepartureTimeASC',
                         'DepartureTimeDESC',
                         'ArrivalTimeASC',
                         'ArrivalTimeDESC',
                         'Airlines']
                    )
FlightsResultsSorter = named_tuple_sex(
    FlightsResultsSorter('TotalPrice', SortOrder.ASC),
    FlightsResultsSorter('Transfers', SortOrder.ASC),
    FlightsResultsSorter('FlightTime', SortOrder.ASC),
    FlightsResultsSorter('DepartureTime', SortOrder.ASC),
    FlightsResultsSorter('DepartureTime', SortOrder.DESC),
    FlightsResultsSorter('ArrivalTime', SortOrder.ASC),
    FlightsResultsSorter('ArrivalTime', SortOrder.DESC),
    FlightsResultsSorter('Airlines', SortOrder.ASC)
)

and in another module I iterate by this collection and I want to get name of item:

for x in FlightsResultsSorter:
            self.sort(x)

so in upon code I want instead x(which is object) passing for example "DepartureTimeASC" or "ArrivalTimeASC".

How can I get this name ?

Best regards

Answer

ars picture ars · Jul 4, 2011

If you're trying to get the actual names, use the _fields attribute:

In [50]: point = collections.namedtuple('point', 'x, y')

In [51]: p = point(x=1, y=2)

In [52]: for name in p._fields:
   ....:     print name, getattr(p, name)
   ....:
x 1
y 2