mirror of
https://github.com/python/cpython.git
synced 2025-09-26 10:19:53 +00:00
Add error-checking to namedtuple's _replace() method.
This commit is contained in:
parent
02740f73ff
commit
1b50fd7cb3
3 changed files with 15 additions and 2 deletions
|
@ -78,7 +78,10 @@ def namedtuple(typename, field_names, verbose=False):
|
|||
return {%(dicttxt)s} \n
|
||||
def _replace(self, **kwds):
|
||||
'Return a new %(typename)s object replacing specified fields with new values'
|
||||
return self.__class__._make(map(kwds.get, %(field_names)r, self)) \n\n''' % locals()
|
||||
result = self.__class__._make(map(kwds.pop, %(field_names)r, self))
|
||||
if kwds:
|
||||
raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
|
||||
return result \n\n''' % locals()
|
||||
for i, name in enumerate(field_names):
|
||||
template += ' %s = property(itemgetter(%d))\n' % (name, i)
|
||||
if verbose:
|
||||
|
|
|
@ -55,6 +55,13 @@ class TestNamedTuple(unittest.TestCase):
|
|||
self.assertEqual(p._replace(x=1), (1, 22)) # test _replace method
|
||||
self.assertEqual(p._asdict(), dict(x=11, y=22)) # test _asdict method
|
||||
|
||||
try:
|
||||
p._replace(x=1, error=2)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
self._fail('Did not detect an incorrect fieldname')
|
||||
|
||||
# verify that field string can have commas
|
||||
Point = namedtuple('Point', 'x, y')
|
||||
p = Point(x=11, y=22)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue