Skip to content

gh-85294: Handle missing arguments to @singledispatchmethod gracefully #21471

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Feb 16, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Lib/functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -883,6 +883,7 @@ def wrapper(*args, **kw):
wrapper.dispatch = dispatch
wrapper.registry = types.MappingProxyType(registry)
wrapper._clear_cache = dispatch_cache.clear
wrapper._funcname = funcname
update_wrapper(wrapper, func)
return wrapper

Expand Down Expand Up @@ -911,6 +912,9 @@ def register(self, cls, method=None):

def __get__(self, obj, cls=None):
def _method(*args, **kwargs):
if not args:
raise TypeError(f'{self.dispatcher._funcname} requires at least '
'1 positional argument')
method = self.dispatcher.dispatch(args[0].__class__)
return method.__get__(obj, cls)(*args, **kwargs)

Expand Down
12 changes: 12 additions & 0 deletions Lib/test/test_functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -2449,6 +2449,18 @@ def f(*args):
with self.assertRaisesRegex(TypeError, msg):
f()

def test_invalid_positional_argument_singlemethoddispatch(self):
class A:
@functools.singledispatchmethod
def t(self):
pass
@t.register
def _(self, arg: int):
return "int"

msg = 't requires at least 1 positional argument'
with self.assertRaisesRegex(TypeError, msg):
A().t()

class CachedCostItem:
_cost = 1
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Failing to pass arguments properly to functools.singledispatchmethod
now throws a TypeError instead of hitting an index out of bounds
internally.