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

Minor named tuple clean-ups.

üst fef85460
...@@ -711,7 +711,7 @@ they add the ability to access fields by name instead of position index. ...@@ -711,7 +711,7 @@ they add the ability to access fields by name instead of position index.
>>> p = Point(x=10, y=11) >>> p = Point(x=10, y=11)
>>> # Example using the verbose option to print the class definition >>> # Example using the verbose option to print the class definition
>>> Point = namedtuple('Point', 'x y', verbose=True) >>> Point = namedtuple('Point', ['x', 'y'], verbose=True)
class Point(tuple): class Point(tuple):
'Point(x, y)' 'Point(x, y)'
<BLANKLINE> <BLANKLINE>
...@@ -743,7 +743,7 @@ they add the ability to access fields by name instead of position index. ...@@ -743,7 +743,7 @@ they add the ability to access fields by name instead of position index.
'Return a new Point object replacing specified fields with new values' 'Return a new Point object replacing specified fields with new values'
result = _self._make(map(kwds.pop, ('x', 'y'), _self)) result = _self._make(map(kwds.pop, ('x', 'y'), _self))
if kwds: if kwds:
raise ValueError('Got unexpected field names: %r' % list(kwds.keys())) raise ValueError('Got unexpected field names: %r' % list(kwds))
return result return result
<BLANKLINE> <BLANKLINE>
def __getnewargs__(self): def __getnewargs__(self):
...@@ -751,6 +751,7 @@ they add the ability to access fields by name instead of position index. ...@@ -751,6 +751,7 @@ they add the ability to access fields by name instead of position index.
return tuple(self) return tuple(self)
<BLANKLINE> <BLANKLINE>
x = _property(_itemgetter(0), doc='Alias for field number 0') x = _property(_itemgetter(0), doc='Alias for field number 0')
<BLANKLINE>
y = _property(_itemgetter(1), doc='Alias for field number 1') y = _property(_itemgetter(1), doc='Alias for field number 1')
>>> p = Point(11, y=22) # instantiate with positional or keyword arguments >>> p = Point(11, y=22) # instantiate with positional or keyword arguments
...@@ -867,7 +868,6 @@ a fixed-width print format: ...@@ -867,7 +868,6 @@ a fixed-width print format:
The subclass shown above sets ``__slots__`` to an empty tuple. This helps The subclass shown above sets ``__slots__`` to an empty tuple. This helps
keep memory requirements low by preventing the creation of instance dictionaries. keep memory requirements low by preventing the creation of instance dictionaries.
Subclassing is not useful for adding new, stored fields. Instead, simply Subclassing is not useful for adding new, stored fields. Instead, simply
create a new named tuple type from the :attr:`_fields` attribute: create a new named tuple type from the :attr:`_fields` attribute:
...@@ -879,6 +879,7 @@ customize a prototype instance: ...@@ -879,6 +879,7 @@ customize a prototype instance:
>>> Account = namedtuple('Account', 'owner balance transaction_count') >>> Account = namedtuple('Account', 'owner balance transaction_count')
>>> default_account = Account('<owner name>', 0.0, 0) >>> default_account = Account('<owner name>', 0.0, 0)
>>> johns_account = default_account._replace(owner='John') >>> johns_account = default_account._replace(owner='John')
>>> janes_account = default_account._replace(owner='Jane')
Enumerated constants can be implemented with named tuples, but it is simpler Enumerated constants can be implemented with named tuples, but it is simpler
and more efficient to use a simple class declaration: and more efficient to use a simple class declaration:
......
...@@ -265,7 +265,7 @@ class {typename}(tuple): ...@@ -265,7 +265,7 @@ class {typename}(tuple):
'Return a new {typename} object replacing specified fields with new values' 'Return a new {typename} object replacing specified fields with new values'
result = _self._make(map(kwds.pop, {field_names!r}, _self)) result = _self._make(map(kwds.pop, {field_names!r}, _self))
if kwds: if kwds:
raise ValueError('Got unexpected field names: %r' % kwds.keys()) raise ValueError('Got unexpected field names: %r' % list(kwds))
return result return result
def __getnewargs__(self): def __getnewargs__(self):
...@@ -309,18 +309,17 @@ def namedtuple(typename, field_names, verbose=False, rename=False): ...@@ -309,18 +309,17 @@ def namedtuple(typename, field_names, verbose=False, rename=False):
# generating informative error messages and preventing template injection attacks. # generating informative error messages and preventing template injection attacks.
if isinstance(field_names, str): if isinstance(field_names, str):
field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
field_names = tuple(map(str, field_names)) field_names = list(map(str, field_names))
if rename: if rename:
names = list(field_names)
seen = set() seen = set()
for i, name in enumerate(names): for index, name in enumerate(field_names):
if (not all(c.isalnum() or c=='_' for c in name) or _iskeyword(name) 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 not name or name[0].isdigit() or name.startswith('_')
or name in seen): or name in seen):
names[i] = '_%d' % i field_names[index] = '_%d' % index
seen.add(name) seen.add(name)
field_names = tuple(names) for name in [typename] + field_names:
for name in (typename,) + field_names:
if not all(c.isalnum() or c=='_' for c in name): 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) raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
if _iskeyword(name): if _iskeyword(name):
...@@ -338,9 +337,9 @@ def namedtuple(typename, field_names, verbose=False, rename=False): ...@@ -338,9 +337,9 @@ def namedtuple(typename, field_names, verbose=False, rename=False):
# Fill-in the class template # Fill-in the class template
class_definition = _class_template.format( class_definition = _class_template.format(
typename = typename, typename = typename,
field_names = field_names, field_names = tuple(field_names),
num_fields = len(field_names), num_fields = len(field_names),
arg_list = repr(field_names).replace("'", "")[1:-1], arg_list = repr(tuple(field_names)).replace("'", "")[1:-1],
repr_fmt = ', '.join(_repr_template.format(name=name) for name in field_names), repr_fmt = ', '.join(_repr_template.format(name=name) for name in field_names),
field_defs = '\n'.join(_field_template.format(index=index, name=name) field_defs = '\n'.join(_field_template.format(index=index, name=name)
for index, name in enumerate(field_names)) for index, name in enumerate(field_names))
......
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