Kaydet (Commit) 2115bbc4 authored tarafından Raymond Hettinger's avatar Raymond Hettinger

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).
üst a970c221
......@@ -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.
......
......@@ -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
......
......@@ -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)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment