Skip to content

gh-85160: improve performance of singledispatchmethod #106448

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 7 commits 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
5 changes: 5 additions & 0 deletions Lib/functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -933,6 +933,7 @@ def __init__(self, func):

self.dispatcher = singledispatch(func)
self.func = func
self._dispatch_method = None

def register(self, cls, method=None):
"""generic_method.register(cls, func) -> func
Expand All @@ -942,13 +943,17 @@ def register(self, cls, method=None):
return self.dispatcher.register(cls, func=method)

def __get__(self, obj, cls=None):
if self._dispatch_method:
return self._dispatch_method

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

_method.__isabstractmethod__ = self.__isabstractmethod__
_method.register = self.register
update_wrapper(_method, self.func)
self._dispatch_method = _method
return _method

@property
Expand Down
20 changes: 20 additions & 0 deletions Lib/test/test_functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -2474,6 +2474,26 @@ def _(arg):
self.assertTrue(A.t(''))
self.assertEqual(A.t(0.0), 0.0)

def test_staticmethod__slotted_class(self):
class A:
__slots__ = ['a']
@functools.singledispatchmethod
def t(arg):
return arg
@t.register(int)
@staticmethod
def _(arg):
return isinstance(arg, int)
@t.register(str)
@staticmethod
def _(arg):
return isinstance(arg, str)
a = A()

self.assertTrue(A.t(0))
self.assertTrue(A.t(''))
self.assertEqual(A.t(0.0), 0.0)

def test_classmethod_register(self):
class A:
def __init__(self, arg):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improve performance of :class:`functools.singledispatchmethod`.