post #931 of 931
From the Python 3.4 documentation:
Quote:
collections.namedtuple(typename, field_names, verbose=False, rename=False)
Returns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable.

So you use the function namedtuple to create an object similar to a tuple in usage and performance but with more flexibility. For me, this has eliminated the need for using overly complex data structures (dictionary of tuples, tuple of dictionaries, etc.) or writing an overly simple class definition just for attributes, in some scenerios.

For example, I'm currently refining a script that includes a function for parsing a structured file, which returns data based on certain search strings. Each line has three specifically categorized fields. My original 'ugly' code returned a tuple of tuples. That is not necessarily a bad thing; it worked fine, but it did present a need for the next function using this data to have to unpack all of the tuples. I could just use indexes there to eliminate the need for unpacking, but that's what I consider ugly code since anyone reading it would have to examine the input data to determine exactly what the code is doing with it. I could also have defined a five line class, but that is an overkill solution for this simple problem. The Zen of Python states "Simple is better than complex".
Code:
LineData = namedtuple('LineData', ('field1', 'field2', 'field3'))
with open(some_file_path) as the_file:
    return tuple(LineData(*line.split()) for line in the_file
                 if any(search in line for search in search_strings))

...as a generically named example. Using the tuple returned by that code, you could do something like:
Code:
for thing in returned_tuples:
    print(thing.field1, 'corresponds to', thing.field2, 'and', thing.field3)

The next function using this data did not even need to be updated since the namedtuple inherits tuple and can do everything it can. I will be rewriting that function anyway to use attributes of the namedtuple items instead of unpacking though. There's no need for my script to have multiple references to data.
Code:
for thing in returned_tuples:
    field1, field2, field3 = thing
    print(field1, 'corresponds to', field2, 'and', field3)

...still works, but like I said, it's unnecessary.