Python Data Structures and Algorithms
上QQ阅读APP看书,第一时间看更新

Named tuples

The namedtuple method returns a tuple-like object that has fields accessible with named indexes as well as the integer indexes of normal tuples. This allows for code that is, to a certain extent, self-documenting and more readable. It can be especially useful in an application where there is a large number of tuples and we need to easily keep track of what each tuple represents. The namedtuple inherits methods from tuple and it is backward-compatible with tuple.

The field names are passed to the namedtuple method as comma and/or whitespace separated values. They can also be passed as a sequence of strings. Field names are single strings and they can be any legal Python identifier that does not begin with a digit or an underscore. A typical example is shown here:

The namedtuple method take two optional Boolean arguments, verbose and rename. When verbose is set to True then the class definition is printed when it is built. This argument is depreciated in favor of using the __source attribute. When the rename argument is set to True then any invalid field names will be automatically replaced with positional arguments. As an example, we attempt to use def as a field name. This would normally generate an error, but since we have assigned rename to True, the Python interpreter allows this. However, when we attempt to look up the def value, we get a syntax error, since def is a reserved keyword. The illegal field name has been replaced by a field name created by adding an underscore to the positional value:

In addition to the inherited tuple methods, the named tuple also defines three methods of its own, _make() , asdict(), and _replace. These methods begin with an underscore to prevent potential conflicts with field names. The _make() method takes an iterable as an argument and turns it into a named tuple object, for example:

The _asdict method returns an OrderedDict with the field names mapped to index keys and the values mapped to the dictionary values, for example:

The _replace method returns a new instance of the tuple, replacing the specified values, for example:

In[82]:  sl._replace(x=7, z=9)
Out[82]: space2 (x=7, _l=4, z=9)