mirror of
https://github.com/python/cpython.git
synced 2025-08-31 05:58:33 +00:00
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. ........
This commit is contained in:
parent
3a409e91d8
commit
a86f2c06fd
5 changed files with 39 additions and 3 deletions
|
@ -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)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue