gh-110275: Named tuple's __replace__() now raises TypeError for invalid arguments (GH-110299)

This commit is contained in:
Serhiy Storchaka 2023-12-04 13:30:32 +02:00 committed by GitHub
parent da6760bdf5
commit c74e9fb189
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 9 additions and 7 deletions

View File

@ -981,6 +981,10 @@ field names, the method and attribute names start with an underscore.
Named tuples are also supported by generic function :func:`copy.replace`.
.. versionchanged:: 3.13
Raise :exc:`TypeError` instead of :exc:`ValueError` for invalid
keyword arguments.
.. attribute:: somenamedtuple._fields
Tuple of strings listing the field names. Useful for introspection

View File

@ -457,7 +457,7 @@ def namedtuple(typename, field_names, *, rename=False, defaults=None, module=Non
def _replace(self, /, **kwds):
result = self._make(_map(kwds.pop, field_names, self))
if kwds:
raise ValueError(f'Got unexpected field names: {list(kwds)!r}')
raise TypeError(f'Got unexpected field names: {list(kwds)!r}')
return result
_replace.__doc__ = (f'Return a new {typename} object replacing specified '

View File

@ -488,12 +488,8 @@ 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:
with self.assertRaises(TypeError):
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')

View File

@ -952,7 +952,7 @@ class TestReplace(unittest.TestCase):
self.assertEqual(copy.replace(p, x=1), (1, 22))
self.assertEqual(copy.replace(p, y=2), (11, 2))
self.assertEqual(copy.replace(p, x=1, y=2), (1, 2))
with self.assertRaisesRegex(ValueError, 'unexpected field name'):
with self.assertRaisesRegex(TypeError, 'unexpected field name'):
copy.replace(p, x=1, error=2)
def test_dataclass(self):

View File

@ -0,0 +1,2 @@
Named tuple's methods ``_replace()`` and ``__replace__()`` now raise
TypeError instead of ValueError for invalid keyword arguments.