summaryrefslogtreecommitdiffstats
path: root/Lib/collections.py
diff options
context:
space:
mode:
authorBenjamin Peterson <benjamin@python.org>2009-02-10 02:41:10 (GMT)
committerBenjamin Peterson <benjamin@python.org>2009-02-10 02:41:10 (GMT)
commita86f2c06fd08e8aebf3641c1ad2d234425b90c55 (patch)
tree0780de78edaaf79a9dbe66d7b2011a8cbb4c9ddd /Lib/collections.py
parent3a409e91d80b754699c9522217d70abd28d6f4f1 (diff)
downloadcpython-a86f2c06fd08e8aebf3641c1ad2d234425b90c55.zip
cpython-a86f2c06fd08e8aebf3641c1ad2d234425b90c55.tar.gz
cpython-a86f2c06fd08e8aebf3641c1ad2d234425b90c55.tar.bz2
Merged revisions 69466,69480 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk ........ r69466 | raymond.hettinger | 2009-02-09 12:39:41 -0600 (Mon, 09 Feb 2009) | 3 lines Issue 5171: itertools.product docstring missing 'repeat' argument ........ r69480 | raymond.hettinger | 2009-02-09 19:24:05 -0600 (Mon, 09 Feb 2009) | 1 line Issue 1818: collections.namedtuple() to support automatic renaming of invalid fieldnames. ........
Diffstat (limited to 'Lib/collections.py')
-rw-r--r--Lib/collections.py14
1 files changed, 12 insertions, 2 deletions
diff --git a/Lib/collections.py b/Lib/collections.py
index 512cf28..f8392b6 100644
--- a/Lib/collections.py
+++ b/Lib/collections.py
@@ -18,7 +18,7 @@ from itertools import repeat as _repeat, chain as _chain, starmap as _starmap
### namedtuple
################################################################################
-def namedtuple(typename, field_names, verbose=False):
+def namedtuple(typename, field_names, verbose=False, rename=False):
"""Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', 'x y')
@@ -47,6 +47,16 @@ def namedtuple(typename, field_names, verbose=False):
if isinstance(field_names, str):
field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
field_names = tuple(map(str, field_names))
+ if rename:
+ names = list(field_names)
+ seen = set()
+ for i, name in enumerate(names):
+ if (not all(c.isalnum() or c=='_' for c in name) or _iskeyword(name)
+ or not name or name[0].isdigit() or name.startswith('_')
+ or name in seen):
+ names[i] = '_%d' % (i+1)
+ seen.add(name)
+ field_names = tuple(names)
for name in (typename,) + field_names:
if not all(c.isalnum() or c=='_' for c in name):
raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
@@ -56,7 +66,7 @@ def namedtuple(typename, field_names, verbose=False):
raise ValueError('Type names and field names cannot start with a number: %r' % name)
seen_names = set()
for name in field_names:
- if name.startswith('_'):
+ if name.startswith('_') and not rename:
raise ValueError('Field names cannot start with an underscore: %r' % name)
if name in seen_names:
raise ValueError('Encountered duplicate field name: %r' % name)