Reading the changes in Python 3.1, I found something… unexpected:
The sys.version_info tuple is now a named tuple:
I never heard about named tuples before, and I thought elements could either be indexed by numbers (like in tuples and lists) or by keys (like in dicts). I never expected they could be indexed both ways.
Thus, my questions are:
- What are named tuples?
- How to use them?
- Why/when should I use named tuples instead of normal tuples?
- Why/when should I use normal tuples instead of named tuples?
- Is there any kind of "named list" (a mutable version of the named tuple)?
Best Answer
Named tuples are basically easy-to-create, lightweight object types. Named tuple instances can be referenced using object-like variable dereferencing or the standard tuple syntax. They can be used similarly to
struct
or other common record types, except that they are immutable. They were added in Python 2.6 and Python 3.0, although there is a recipe for implementation in Python 2.4.For example, it is common to represent a point as a tuple
(x, y)
. This leads to code like the following:Using a named tuple it becomes more readable:
However, named tuples are still backwards compatible with normal tuples, so the following will still work:
Thus, you should use named tuples instead of tuples anywhere you think object notation will make your code more pythonic and more easily readable. I personally have started using them to represent very simple value types, particularly when passing them as parameters to functions. It makes the functions more readable, without seeing the context of the tuple packing.
Furthermore, you can also replace ordinary immutable classes that have no functions, only fields with them. You can even use your named tuple types as base classes:
However, as with tuples, attributes in named tuples are immutable:
If you want to be able change the values, you need another type. There is a handy recipe for mutable recordtypes which allow you to set new values to attributes.
I am not aware of any form of "named list" that lets you add new fields, however. You may just want to use a dictionary in this situation. Named tuples can be converted to dictionaries using
pt1._asdict()
which returns{'x': 1.0, 'y': 5.0}
and can be operated upon with all the usual dictionary functions.As already noted, you should check the documentation for more information from which these examples were constructed.