Skip to content

Commit c74e9fb

Browse files
gh-110275: Named tuple's __replace__() now raises TypeError for invalid arguments (GH-110299)
1 parent da6760b commit c74e9fb

File tree

5 files changed

+9
-7
lines changed

5 files changed

+9
-7
lines changed

Doc/library/collections.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -981,6 +981,10 @@ field names, the method and attribute names start with an underscore.
981981

982982
Named tuples are also supported by generic function :func:`copy.replace`.
983983

984+
.. versionchanged:: 3.13
985+
Raise :exc:`TypeError` instead of :exc:`ValueError` for invalid
986+
keyword arguments.
987+
984988
.. attribute:: somenamedtuple._fields
985989

986990
Tuple of strings listing the field names. Useful for introspection

Lib/collections/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -457,7 +457,7 @@ def _make(cls, iterable):
457457
def _replace(self, /, **kwds):
458458
result = self._make(_map(kwds.pop, field_names, self))
459459
if kwds:
460-
raise ValueError(f'Got unexpected field names: {list(kwds)!r}')
460+
raise TypeError(f'Got unexpected field names: {list(kwds)!r}')
461461
return result
462462

463463
_replace.__doc__ = (f'Return a new {typename} object replacing specified '

Lib/test/test_collections.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -488,12 +488,8 @@ def test_instance(self):
488488
self.assertEqual(p._replace(x=1), (1, 22)) # test _replace method
489489
self.assertEqual(p._asdict(), dict(x=11, y=22)) # test _asdict method
490490

491-
try:
491+
with self.assertRaises(TypeError):
492492
p._replace(x=1, error=2)
493-
except ValueError:
494-
pass
495-
else:
496-
self._fail('Did not detect an incorrect fieldname')
497493

498494
# verify that field string can have commas
499495
Point = namedtuple('Point', 'x, y')

Lib/test/test_copy.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -952,7 +952,7 @@ class PointFromClass(NamedTuple):
952952
self.assertEqual(copy.replace(p, x=1), (1, 22))
953953
self.assertEqual(copy.replace(p, y=2), (11, 2))
954954
self.assertEqual(copy.replace(p, x=1, y=2), (1, 2))
955-
with self.assertRaisesRegex(ValueError, 'unexpected field name'):
955+
with self.assertRaisesRegex(TypeError, 'unexpected field name'):
956956
copy.replace(p, x=1, error=2)
957957

958958
def test_dataclass(self):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Named tuple's methods ``_replace()`` and ``__replace__()`` now raise
2+
TypeError instead of ValueError for invalid keyword arguments.

0 commit comments

Comments
 (0)