Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b2d0945

Browse files
committed
Minor named tuple clean-ups.
1 parent fef8546 commit b2d0945

2 files changed

Lines changed: 42 additions & 42 deletions

File tree

Doc/library/collections.rst

Lines changed: 33 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -711,47 +711,48 @@ they add the ability to access fields by name instead of position index.
711711
>>> p = Point(x=10, y=11)
712712

713713
>>> # Example using the verbose option to print the class definition
714-
>>> Point = namedtuple('Point', 'x y', verbose=True)
714+
>>> Point = namedtuple('Point', ['x', 'y'], verbose=True)
715715
class Point(tuple):
716-
'Point(x, y)'
716+
'Point(x, y)'
717717
<BLANKLINE>
718-
__slots__ = ()
718+
__slots__ = ()
719719
<BLANKLINE>
720-
_fields = ('x', 'y')
720+
_fields = ('x', 'y')
721721
<BLANKLINE>
722-
def __new__(_cls, x, y):
723-
'Create a new instance of Point(x, y)'
724-
return _tuple.__new__(_cls, (x, y))
722+
def __new__(_cls, x, y):
723+
'Create a new instance of Point(x, y)'
724+
return _tuple.__new__(_cls, (x, y))
725725
<BLANKLINE>
726-
@classmethod
727-
def _make(cls, iterable, new=tuple.__new__, len=len):
728-
'Make a new Point object from a sequence or iterable'
729-
result = new(cls, iterable)
730-
if len(result) != 2:
731-
raise TypeError('Expected 2 arguments, got %d' % len(result))
732-
return result
726+
@classmethod
727+
def _make(cls, iterable, new=tuple.__new__, len=len):
728+
'Make a new Point object from a sequence or iterable'
729+
result = new(cls, iterable)
730+
if len(result) != 2:
731+
raise TypeError('Expected 2 arguments, got %d' % len(result))
732+
return result
733733
<BLANKLINE>
734-
def __repr__(self):
735-
'Return a nicely formatted representation string'
736-
return self.__class__.__name__ + '(x=%r, y=%r)' % self
734+
def __repr__(self):
735+
'Return a nicely formatted representation string'
736+
return self.__class__.__name__ + '(x=%r, y=%r)' % self
737737
<BLANKLINE>
738-
def _asdict(self):
739-
'Return a new OrderedDict which maps field names to their values'
740-
return OrderedDict(zip(self._fields, self))
738+
def _asdict(self):
739+
'Return a new OrderedDict which maps field names to their values'
740+
return OrderedDict(zip(self._fields, self))
741741
<BLANKLINE>
742-
def _replace(_self, **kwds):
743-
'Return a new Point object replacing specified fields with new values'
744-
result = _self._make(map(kwds.pop, ('x', 'y'), _self))
745-
if kwds:
746-
raise ValueError('Got unexpected field names: %r' % list(kwds.keys()))
747-
return result
742+
def _replace(_self, **kwds):
743+
'Return a new Point object replacing specified fields with new values'
744+
result = _self._make(map(kwds.pop, ('x', 'y'), _self))
745+
if kwds:
746+
raise ValueError('Got unexpected field names: %r' % list(kwds))
747+
return result
748748
<BLANKLINE>
749-
def __getnewargs__(self):
750-
'Return self as a plain tuple. Used by copy and pickle.'
751-
return tuple(self)
749+
def __getnewargs__(self):
750+
'Return self as a plain tuple. Used by copy and pickle.'
751+
return tuple(self)
752752
<BLANKLINE>
753-
x = _property(_itemgetter(0), doc='Alias for field number 0')
754-
y = _property(_itemgetter(1), doc='Alias for field number 1')
753+
x = _property(_itemgetter(0), doc='Alias for field number 0')
754+
<BLANKLINE>
755+
y = _property(_itemgetter(1), doc='Alias for field number 1')
755756

756757
>>> p = Point(11, y=22) # instantiate with positional or keyword arguments
757758
>>> p[0] + p[1] # indexable like the plain tuple (11, 22)
@@ -867,7 +868,6 @@ a fixed-width print format:
867868
The subclass shown above sets ``__slots__`` to an empty tuple. This helps
868869
keep memory requirements low by preventing the creation of instance dictionaries.
869870

870-
871871
Subclassing is not useful for adding new, stored fields. Instead, simply
872872
create a new named tuple type from the :attr:`_fields` attribute:
873873

@@ -879,6 +879,7 @@ customize a prototype instance:
879879
>>> Account = namedtuple('Account', 'owner balance transaction_count')
880880
>>> default_account = Account('<owner name>', 0.0, 0)
881881
>>> johns_account = default_account._replace(owner='John')
882+
>>> janes_account = default_account._replace(owner='Jane')
882883

883884
Enumerated constants can be implemented with named tuples, but it is simpler
884885
and more efficient to use a simple class declaration:

Lib/collections/__init__.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ def _replace(_self, **kwds):
265265
'Return a new {typename} object replacing specified fields with new values'
266266
result = _self._make(map(kwds.pop, {field_names!r}, _self))
267267
if kwds:
268-
raise ValueError('Got unexpected field names: %r' % kwds.keys())
268+
raise ValueError('Got unexpected field names: %r' % list(kwds))
269269
return result
270270
271271
def __getnewargs__(self):
@@ -309,18 +309,17 @@ def namedtuple(typename, field_names, verbose=False, rename=False):
309309
# generating informative error messages and preventing template injection attacks.
310310
if isinstance(field_names, str):
311311
field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
312-
field_names = tuple(map(str, field_names))
312+
field_names = list(map(str, field_names))
313313
if rename:
314-
names = list(field_names)
315314
seen = set()
316-
for i, name in enumerate(names):
317-
if (not all(c.isalnum() or c=='_' for c in name) or _iskeyword(name)
315+
for index, name in enumerate(field_names):
316+
if (not all(c.isalnum() or c=='_' for c in name)
317+
or _iskeyword(name)
318318
or not name or name[0].isdigit() or name.startswith('_')
319319
or name in seen):
320-
names[i] = '_%d' % i
320+
field_names[index] = '_%d' % index
321321
seen.add(name)
322-
field_names = tuple(names)
323-
for name in (typename,) + field_names:
322+
for name in [typename] + field_names:
324323
if not all(c.isalnum() or c=='_' for c in name):
325324
raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
326325
if _iskeyword(name):
@@ -338,9 +337,9 @@ def namedtuple(typename, field_names, verbose=False, rename=False):
338337
# Fill-in the class template
339338
class_definition = _class_template.format(
340339
typename = typename,
341-
field_names = field_names,
340+
field_names = tuple(field_names),
342341
num_fields = len(field_names),
343-
arg_list = repr(field_names).replace("'", "")[1:-1],
342+
arg_list = repr(tuple(field_names)).replace("'", "")[1:-1],
344343
repr_fmt = ', '.join(_repr_template.format(name=name) for name in field_names),
345344
field_defs = '\n'.join(_field_template.format(index=index, name=name)
346345
for index, name in enumerate(field_names))

0 commit comments

Comments
 (0)