Skip to content
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

gh-85160: Optimized singledispatchmethod access (noticeable improvement). #23213

Closed
wants to merge 2 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
13 changes: 13 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.attrname = None

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

def __set_name__(self, _, name):
self.attrname = name

def __get__(self, obj, cls=None):
def _method(*args, **kwargs):
method = self.dispatcher.dispatch(args[0].__class__)
Expand All @@ -949,6 +953,15 @@ def _method(*args, **kwargs):
_method.__isabstractmethod__ = self.__isabstractmethod__
_method.register = self.register
update_wrapper(_method, self.func)

if self.attrname is not None:
attrname = self.attrname

try:
obj.__dict__[attrname] = _method
except AttributeError:
pass # not all objects have __dict__ (e.g. class defines slots)
Comment on lines +957 to +963
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if self.attrname is not None:
attrname = self.attrname
try:
obj.__dict__[attrname] = _method
except AttributeError:
pass # not all objects have __dict__ (e.g. class defines slots)
if self.attrname is not None:
try:
obj.__dict__[self.attrname] = _method
except AttributeError:
pass # not all objects have __dict__ (e.g. class defines slots)


return _method

@property
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Applied a cached_propery type optimization suggested by federico to
singledispatchmethod yielding approximately a 3.5 speedup in access times.
Loading