diff options
author | Raymond Hettinger <python@rcn.com> | 2007-05-19 01:11:16 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2007-05-19 01:11:16 (GMT) |
commit | 5a41daf096d7fe7cb8d7624640cdc6bec74003c1 (patch) | |
tree | e66587812905fb2bb86996079ce8a3b343734c7e /Doc | |
parent | 6290305e6722c20e17d3c73bd6a30c6448bead83 (diff) | |
download | cpython-5a41daf096d7fe7cb8d7624640cdc6bec74003c1.zip cpython-5a41daf096d7fe7cb8d7624640cdc6bec74003c1.tar.gz cpython-5a41daf096d7fe7cb8d7624640cdc6bec74003c1.tar.bz2 |
Improvements to NamedTuple's implementation, tests, and documentation
Diffstat (limited to 'Doc')
-rw-r--r-- | Doc/lib/libcollections.tex | 19 |
1 files changed, 15 insertions, 4 deletions
diff --git a/Doc/lib/libcollections.tex b/Doc/lib/libcollections.tex index 443a7a4..c0eb6ec 100644 --- a/Doc/lib/libcollections.tex +++ b/Doc/lib/libcollections.tex @@ -378,14 +378,25 @@ Point(x=11, y=22) The use cases are the same as those for tuples. The named factories assign meaning to each tuple position and allow for more readable, self-documenting code. Named tuples can also be used to assign field names - to tuples - returned by the \module{csv} or \module{sqlite3} modules. For example: + to tuples returned by the \module{csv} or \module{sqlite3} modules. + For example: \begin{verbatim} +from itertools import starmap import csv EmployeeRecord = NamedTuple('EmployeeRecord', 'name age title department paygrade') -for tup in csv.reader(open("employees.csv", "rb")): - print EmployeeRecord(*tup) +for record in starmap(EmployeeRecord, csv.reader(open("employees.csv", "rb"))): + print record +\end{verbatim} + + To cast an individual record stored as \class{list}, \class{tuple}, or some other + iterable type, use the star-operator to unpack the values: + + \begin{verbatim} +>>> Color = NamedTuple('Color', 'name code') +>>> m = dict(red=1, green=2, blue=3) +>>> print Color(*m.popitem()) +Color(name='blue', code=3) \end{verbatim} \end{funcdesc} |