[Python-checkins] r58370 - in python/trunk: Doc/library/collections.rst Lib/collections.py Lib/test/test_collections.py

raymond.hettinger python-checkins at python.org
Mon Oct 8 11:14:28 CEST 2007


Author: raymond.hettinger
Date: Mon Oct  8 11:14:28 2007
New Revision: 58370

Modified:
   python/trunk/Doc/library/collections.rst
   python/trunk/Lib/collections.py
   python/trunk/Lib/test/test_collections.py
Log:
Add comments to NamedTuple code.
Let the field spec be either a string or a non-string sequence (suggested by Martin Blais with use cases).
Improve the error message in the case of a SyntaxError (caused by a duplicate field name).



Modified: python/trunk/Doc/library/collections.rst
==============================================================================
--- python/trunk/Doc/library/collections.rst	(original)
+++ python/trunk/Doc/library/collections.rst	Mon Oct  8 11:14:28 2007
@@ -363,9 +363,11 @@
    helpful docstring (with typename and fieldnames) and a helpful :meth:`__repr__`
    method which lists the tuple contents in a ``name=value`` format.
 
-   The *fieldnames* are specified in a single string with each fieldname separated by
-   a space and/or comma.  Any valid Python identifier may be used for a fieldname
-   except for names starting and ending with double underscores.
+   The *fieldnames* are a single string with each fieldname separated by a space
+   and/or comma (for example "x y" or "x, y").  Alternately, the *fieldnames*
+   can be specified as list or tuple of strings.  Any valid Python identifier
+   may be used for a fieldname except for names starting and ending with double
+   underscores.
 
    If *verbose* is true, will print the class definition.
 

Modified: python/trunk/Lib/collections.py
==============================================================================
--- python/trunk/Lib/collections.py	(original)
+++ python/trunk/Lib/collections.py	Mon Oct  8 11:14:28 2007
@@ -4,7 +4,7 @@
 from operator import itemgetter as _itemgetter
 import sys as _sys
 
-def NamedTuple(typename, s, verbose=False):
+def NamedTuple(typename, field_names, verbose=False):
     """Returns a new subclass of tuple with named fields.
 
     >>> Point = NamedTuple('Point', 'x y')
@@ -28,11 +28,16 @@
 
     """
 
-    field_names = tuple(s.replace(',', ' ').split())    # names separated by spaces and/or commas
+    # Parse and validate the field names
+    if isinstance(field_names, basestring):
+        field_names = s.replace(',', ' ').split()       # names separated by spaces and/or commas
+    field_names = tuple(field_names)
     if not ''.join((typename,) + field_names).replace('_', '').isalnum():
         raise ValueError('Type names and field names can only contain alphanumeric characters and underscores')
     if any(name.startswith('__') and name.endswith('__') for name in field_names):
         raise ValueError('Field names cannot start and end with double underscores')
+
+    # Create and fill-in the class template
     argtxt = repr(field_names).replace("'", "")[1:-1]   # tuple repr without parens or quotes
     reprtxt = ', '.join('%s=%%r' % name for name in field_names)
     template = '''class %(typename)s(tuple):
@@ -53,11 +58,21 @@
         template += '        %s = property(itemgetter(%d))\n' % (name, i)
     if verbose:
         print template
+
+    # Execute the template string in a temporary namespace
     m = dict(itemgetter=_itemgetter)
-    exec template in m
+    try:
+        exec template in m
+    except SyntaxError, e:
+        raise SyntaxError(e.message + ':\n' + template)
     result = m[typename]
+
+    # For pickling to work, the __module__ variable needs to be set to the frame
+    # where the named tuple is created.  Bypass this step in enviroments where
+    # sys._getframe is not defined (Jython for example).
     if hasattr(_sys, '_getframe'):
         result.__module__ = _sys._getframe(1).f_globals['__name__']
+
     return result
 
 

Modified: python/trunk/Lib/test/test_collections.py
==============================================================================
--- python/trunk/Lib/test/test_collections.py	(original)
+++ python/trunk/Lib/test/test_collections.py	Mon Oct  8 11:14:28 2007
@@ -40,6 +40,11 @@
         p = Point(x=11, y=22)
         self.assertEqual(repr(p), 'Point(x=11, y=22)')
 
+        # verify that fieldspec can be a non-string sequence
+        Point = NamedTuple('Point', ('x', 'y'))
+        p = Point(x=11, y=22)
+        self.assertEqual(repr(p), 'Point(x=11, y=22)')
+
     def test_tupleness(self):
         Point = NamedTuple('Point', 'x y')
         p = Point(11, 22)


More information about the Python-checkins mailing list