diff options
-rw-r--r-- | Doc/library/collections.rst | 8 | ||||
-rw-r--r-- | Lib/collections.py | 21 | ||||
-rw-r--r-- | Lib/test/test_collections.py | 5 |
3 files changed, 28 insertions, 6 deletions
diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst index fc5bbebfe1..5da7b60a55 100644 --- a/Doc/library/collections.rst +++ b/Doc/library/collections.rst @@ -363,9 +363,11 @@ they add the ability to access fields by name instead of position index. 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. diff --git a/Lib/collections.py b/Lib/collections.py index 7b10712317..c5eb79cd72 100644 --- a/Lib/collections.py +++ b/Lib/collections.py @@ -4,7 +4,7 @@ from _collections import deque, defaultdict 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 @@ def NamedTuple(typename, s, verbose=False): """ - 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 @@ def NamedTuple(typename, s, verbose=False): 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 diff --git a/Lib/test/test_collections.py b/Lib/test/test_collections.py index 939c3cebff..c260bc78ff 100644 --- a/Lib/test/test_collections.py +++ b/Lib/test/test_collections.py @@ -40,6 +40,11 @@ class TestNamedTuple(unittest.TestCase): 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) |