Named Tuples are awesome. They allow a coder to create very ad-hoc data structures while carrying enough identity information in the structure to treat them like types.
Here I create a Person type out of a named tuple.
>>> from collections import namedtuple
>>> Person = namedtuple('Person', 'first_name last_name user_id')
>>> p = Person('James', 'Dennis', 'j2d2')
Person(first_name='James', last_name='Dennis', user_id='j2d2')
Even though it looks like a class, it’s still a tuple. I’ll access the first_name field via an index.
And check it out, pattern matching to pull data out of a tuple works too.
>>> first, last, user_id = p
So why would we use a namedtuple?
Well, I can access the tuple’s members by names, which is easier to think about than maintaining “p is first_name” in my head for multiple structures over time. I want to think about a person and have my code reflect that.
I’ll access the first name field by it’s name, first_name.
I love abilities like this because structures of data will always be necessary, but it’s not easy to build them on the fly without having to commit to something along the lines of a class OR simply memorizing a lot of arbitrary tuple indexes.