]> granicus.if.org Git - python/commitdiff
Issue 2909: show how to name unpacked fields.
authorRaymond Hettinger <python@rcn.com>
Fri, 23 May 2008 17:21:44 +0000 (17:21 +0000)
committerRaymond Hettinger <python@rcn.com>
Fri, 23 May 2008 17:21:44 +0000 (17:21 +0000)
Doc/library/struct.rst

index e2443aa3950e02fc566d8e12b2bbe847194c2300..63bf9b178e2cf559d3d058840a302796ef3315ad 100644 (file)
@@ -233,6 +233,16 @@ end, assuming longs are aligned on 4-byte boundaries.  This only works when
 native size and alignment are in effect; standard size and alignment does not
 enforce any alignment.
 
+Unpacked fields can be named by assigning them to variables or by wrapping
+the result in a named tuple::
+
+    >>> record = 'raymond   \x32\x12\x08\x01\x08'
+    >>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)
+
+    >>> from collections import namedtuple
+    >>> Student = namedtuple('Student', 'name serialnum school gradelevel')
+    >>> Student._make(unpack('<10sHHb', s))
+    Student(name='raymond   ', serialnum=4658, school=264, gradelevel=8)
 
 .. seealso::