From: Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> Date: Tue, 10 Jul 2018 08:00:35 +0000 (-0700) Subject: bpo-33967: Fix singledispatch raised IndexError when no args (GH-8184) X-Git-Tag: v3.6.7rc1~186 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=6ceab46a602c6653356d67d7479391fba0b35697;p=python bpo-33967: Fix singledispatch raised IndexError when no args (GH-8184) (cherry picked from commit 445f1b35ce8461268438c8a6b327ddc764287e05) Co-authored-by: Dong-hee Na --- diff --git a/Lib/functools.py b/Lib/functools.py index 89f2cf4f5f..784628829d 100644 --- a/Lib/functools.py +++ b/Lib/functools.py @@ -800,8 +800,13 @@ def singledispatch(func): return func def wrapper(*args, **kw): + if not args: + raise TypeError(f'{funcname} requires at least ' + '1 positional argument') + return dispatch(args[0].__class__)(*args, **kw) + funcname = getattr(func, '__name__', 'singledispatch function') registry[object] = func wrapper.register = register wrapper.dispatch = dispatch diff --git a/Lib/test/test_functools.py b/Lib/test/test_functools.py index 145440027c..5e454dd9ab 100644 --- a/Lib/test/test_functools.py +++ b/Lib/test/test_functools.py @@ -2078,6 +2078,13 @@ class TestSingleDispatch(unittest.TestCase): self.assertEqual(len(td), 0) functools.WeakKeyDictionary = _orig_wkd + def test_invalid_positional_argument(self): + @functools.singledispatch + def f(*args): + pass + msg = 'f requires at least 1 positional argument' + with self.assertRaisesRegexp(TypeError, msg): + f() if __name__ == '__main__': unittest.main() diff --git a/Misc/NEWS.d/next/Library/2018-07-08-18-49-41.bpo-33967.lhaAez.rst b/Misc/NEWS.d/next/Library/2018-07-08-18-49-41.bpo-33967.lhaAez.rst new file mode 100644 index 0000000000..1e1e745789 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2018-07-08-18-49-41.bpo-33967.lhaAez.rst @@ -0,0 +1,2 @@ +functools.singledispatch now raises TypeError instead of IndexError when no +positional arguments are passed.