|
1
|
NamedTuple is a tuple subclass that allows its elements to be named. Elements can be accessed by index and by name.
A common usage of tuples is to represent aggregations of heterogenous data, as a kind of anonymous data structure. The built-in tuple type only allows the elements to be accessed by their indices; this leads to a loss of clarity: seeing x[3] in code is less clear than x.middlename, for example. The NamedTuple class allows construction of tuples with named elements. These elements can then be accessed by index or by name, as convenient. For example:
Because NamedTuple is a subclass of tuple, all the standard tuple methods will work on it as usual. This provides the convenience of tuples with the clarity of named elements. |
1 comment
Add a comment
Sign in to comment
Download
Copy to clipboard

Kudos and a Mod. Andrew, this is great! I started working with it and came up with a few mods. Unfortunately I don't know how to appropriately paste code in the comments yet, so I submitted a new recipe (#303770) that details the mods I made. I hope you'll check it out and let me know what you think. Basically, I moved the _names dict to a 'base' class so that all derivations don't need to specify the attribute names at instantiation time. This helps to reduce the clutter when instantiating the tuples. Thanks for sharing!