Skip to content

bpo-41122: Check for required positional argument in singledispatchmethod invocation #23212

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
10 changes: 10 additions & 0 deletions Lib/functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -911,6 +911,16 @@ def register(self, cls, method=None):

def __get__(self, obj, cls=None):
def _method(*args, **kwargs):
funcname = getattr(
self.func,
'__name__',
'singledispatchmethod'
)

if not args:
raise TypeError(f'{funcname!r} requires'
' at least 1 positional argument')

method = self.dispatcher.dispatch(args[0].__class__)
return method.__get__(obj, cls)(*args, **kwargs)

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

class _:
@functools.singledispatchmethod
def f(self, *args):
pass

msg = '\'f\' requires at least 1 positional argument'
with self.assertRaisesRegex(TypeError, msg):
_().f()


class CachedCostItem:
_cost = 1
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
singledispatchmethod decorated methods now raise TypeError with an appropriate
message when called without the required positional argument, previously a
confusing IndexError was propagated to the user.