Skip to content

Commit df9f633

Browse files
bpo-33967: Fix singledispatch raised IndexError when no args (GH-8184)
(cherry picked from commit 445f1b3) Co-authored-by: Dong-hee Na <[email protected]>
1 parent c3bdea4 commit df9f633

File tree

3 files changed

+14
-0
lines changed

3 files changed

+14
-0
lines changed

Lib/functools.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -817,8 +817,13 @@ def register(cls, func=None):
817817
return func
818818

819819
def wrapper(*args, **kw):
820+
if not args:
821+
raise TypeError(f'{funcname} requires at least '
822+
'1 positional argument')
823+
820824
return dispatch(args[0].__class__)(*args, **kw)
821825

826+
funcname = getattr(func, '__name__', 'singledispatch function')
822827
registry[object] = func
823828
wrapper.register = register
824829
wrapper.dispatch = dispatch

Lib/test/test_functools.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2187,6 +2187,13 @@ def _(arg: typing.Iterable[str]):
21872187
))
21882188
self.assertTrue(str(exc.exception).endswith(msg_suffix))
21892189

2190+
def test_invalid_positional_argument(self):
2191+
@functools.singledispatch
2192+
def f(*args):
2193+
pass
2194+
msg = 'f requires at least 1 positional argument'
2195+
with self.assertRaisesRegexp(TypeError, msg):
2196+
f()
21902197

21912198
if __name__ == '__main__':
21922199
unittest.main()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
functools.singledispatch now raises TypeError instead of IndexError when no
2+
positional arguments are passed.

0 commit comments

Comments
 (0)