Skip to content

bpo-32380 Fix singledispatch interaction with methods #4987

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 5 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
19 changes: 18 additions & 1 deletion Doc/library/functools.rst
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ The :mod:`functools` module defines the following functions:
>>> fun_num is fun
False

When called, the generic function dispatches on the type of the first
When called, the generic function by default dispatches on the type of the first
argument::

>>> fun("Hello, world.")
Expand All @@ -357,6 +357,23 @@ The :mod:`functools` module defines the following functions:
for the base ``object`` type, which means it is used if no better
implementation is found.

You can also tell ``@singeldispatch`` to dispatch on another argument index
Copy link
Contributor

Choose a reason for hiding this comment

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

s/singeldispatch/singledispatch/ (typo fix)

with the ``arg`` keyword. This is especially useful for methods::

class Negater:
"""neg(a) negates a for bools and ints"""
@singledispatch(arg=1)
def neg(self, a):
raise NotImplementedError("Cannot negate a")

@neg.register(int)
def _(self, a):
return -a

@neg.register(bool)
def _(self, a):
return not a

To check which implementation will the generic function choose for
a given type, use the ``dispatch()`` attribute::

Expand Down
144 changes: 73 additions & 71 deletions Lib/functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -744,7 +744,7 @@ def _find_impl(cls, registry):
match = t
return registry.get(match)

def singledispatch(func):
def singledispatch(func=None, arg=0):
Copy link
Contributor

Choose a reason for hiding this comment

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

The name arg doesn't clear convey that this is the arg index the will be used to dispatch on. arg_index would be clearer.

(Although this will become a moot point if you switch to a separate singledispatchmethod as proposed below)

"""Single-dispatch generic function decorator.

Transforms a function into a generic function, which can have different
Expand All @@ -753,76 +753,78 @@ def singledispatch(func):
implementations can be registered using the register() attribute of the
Copy link
Contributor

Choose a reason for hiding this comment

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

Docstring needs to be updated for the new parameter

generic function.
"""
# There are many programs that use functools without singledispatch, so we
# trade-off making singledispatch marginally slower for the benefit of
# making start-up of such applications slightly faster.
import types, weakref

registry = {}
dispatch_cache = weakref.WeakKeyDictionary()
cache_token = None

def dispatch(cls):
"""generic_func.dispatch(cls) -> <function implementation>

Runs the dispatch algorithm to return the best available implementation
for the given *cls* registered on *generic_func*.

"""
nonlocal cache_token
if cache_token is not None:
current_token = get_cache_token()
if cache_token != current_token:
dispatch_cache.clear()
cache_token = current_token
try:
impl = dispatch_cache[cls]
except KeyError:
if func is None:
return partial(singledispatch, arg=arg)
else:
# There are many programs that use functools without singledispatch, so we
# trade-off making singledispatch marginally slower for the benefit of
# making start-up of such applications slightly faster.
import types, weakref
registry = {}
dispatch_cache = weakref.WeakKeyDictionary()
cache_token = None

def dispatch(cls):
"""generic_func.dispatch(cls) -> <function implementation>

Runs the dispatch algorithm to return the best available implementation
for the given *cls* registered on *generic_func*.

"""
nonlocal cache_token
if cache_token is not None:
current_token = get_cache_token()
if cache_token != current_token:
dispatch_cache.clear()
cache_token = current_token
try:
impl = registry[cls]
impl = dispatch_cache[cls]
Copy link
Member Author

Choose a reason for hiding this comment

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

This is the diff being weird, I did not change this. The block and main part of singledispatch was indented.

except KeyError:
impl = _find_impl(cls, registry)
dispatch_cache[cls] = impl
return impl

def register(cls, func=None):
"""generic_func.register(cls, func) -> func

Registers a new implementation for the given *cls* on a *generic_func*.

"""
nonlocal cache_token
if func is None:
if isinstance(cls, type):
return lambda f: register(cls, f)
ann = getattr(cls, '__annotations__', {})
if not ann:
raise TypeError(
f"Invalid first argument to `register()`: {cls!r}. "
f"Use either `@register(some_class)` or plain `@register` "
f"on an annotated function."
try:
impl = registry[cls]
except KeyError:
impl = _find_impl(cls, registry)
dispatch_cache[cls] = impl
return impl

def register(cls, func=None):
"""generic_func.register(cls, func) -> func

Registers a new implementation for the given *cls* on a *generic_func*.

"""
nonlocal cache_token
if func is None:
if isinstance(cls, type):
return lambda f: register(cls, f)
ann = getattr(cls, '__annotations__', {})
if not ann:
raise TypeError(
f"Invalid first argument to `register()`: {cls!r}. "
f"Use either `@register(some_class)` or plain `@register` "
f"on an annotated function."
)
func = cls

# only import typing if annotation parsing is necessary
from typing import get_type_hints
argname, cls = next(iter(get_type_hints(func).items()))
assert isinstance(cls, type), (
f"Invalid annotation for {argname!r}. {cls!r} is not a class."
)
func = cls

# only import typing if annotation parsing is necessary
from typing import get_type_hints
argname, cls = next(iter(get_type_hints(func).items()))
assert isinstance(cls, type), (
f"Invalid annotation for {argname!r}. {cls!r} is not a class."
)
registry[cls] = func
if cache_token is None and hasattr(cls, '__abstractmethods__'):
cache_token = get_cache_token()
dispatch_cache.clear()
return func

def wrapper(*args, **kw):
return dispatch(args[0].__class__)(*args, **kw)

registry[object] = func
wrapper.register = register
wrapper.dispatch = dispatch
wrapper.registry = types.MappingProxyType(registry)
wrapper._clear_cache = dispatch_cache.clear
update_wrapper(wrapper, func)
return wrapper
registry[cls] = func
if cache_token is None and hasattr(cls, '__abstractmethods__'):
cache_token = get_cache_token()
dispatch_cache.clear()
return func

def wrapper(*args, **kw):
return dispatch(args[arg].__class__)(*args, **kw)

registry[object] = func
wrapper.register = register
wrapper.dispatch = dispatch
wrapper.registry = types.MappingProxyType(registry)
wrapper._clear_cache = dispatch_cache.clear
update_wrapper(wrapper, func)
return wrapper
37 changes: 37 additions & 0 deletions Lib/test/test_functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -2147,6 +2147,43 @@ def __eq__(self, other):
return self.arg == other
self.assertEqual(i("str"), "str")

def test_method_register(self):
class A:
@functools.singledispatch(arg=1)
def t(self, arg):
return "base"
@t.register(int)
def _(self, arg):
return "int"
@t.register(str)
def _(self, arg):
return "str"
Copy link
Contributor

Choose a reason for hiding this comment

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

As @ilevkivskyi noted, additional tests are needed to cover the interaction with other method decorators, especially classmethod, staticmethod, abstractmethod, and partialmethod.

I think you will find that adding a parameter to the existing singledispatch function isn't going to be sufficient to solve the problem in the general case (including supporting post-registration of new overloads after the class has been defined). Instead, you'll need something more along the lines of partialmethod which is aware of the descriptor protocol, and uses that to delegate to the underlying descriptor's __get__ method as necessary. While it's a bit long, singledispatchmethod would follow the existing convention for descriptor protocol aware variants of previously function-only APIs.

Choose a reason for hiding this comment

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

Hey @ncoghlan and @ethanhs, I'd been lurking the cpython PRs and had some time today, so I made a quick gist of a possible descriptor-aware implementation of singlemethoddispatch. It's far from complete, but it does work for instance, abstract and class methods. (I haven't tried static methods or partial methods yet). I thought I'd link to it here in case it can provide you with some direction / inspiration.

Nice to haves (for my implementation, at least), would be a mechanism which wraps up any methods registered by the decorated method in the same decorators in which that method is wrapped; e.g., if Foo.bar is a classmethod, then Foo.bar.register(int, baz) should make baz a class method too. On the other hand, that's complicated to implement and possibly not even the desired behavior, so I'm putting it on the back-burner for now.

Anyway, here's the gist. Heavily inspired by the partialmethod implementation, as you'll see: https://gist.github.com/ianhoffman/e25899e8fca3c1ef8772f331b14031d0

a = A()

self.assertEqual(a.t(0), "int")
self.assertEqual(a.t(''), "str")
self.assertEqual(a.t(0.0), "base")

self.assertEqual(A.t(a,0), "int")
self.assertEqual(A.t(a,''), "str")
self.assertEqual(A.t(a,0.0), "base")

def test_method_register_noargs(self):
msg = "tuple index out of range"
class B:
@functools.singledispatch(arg=1)
def fun():
return 'base'
@fun.register(str)
def _():
return "str"
@fun.register(float)
def _():
return "float"
with self.assertRaises(IndexError) as exc:
B.fun()
self.assertEqual(str(exc.exception), msg)

def test_invalid_registrations(self):
msg_prefix = "Invalid first argument to `register()`: "
msg_suffix = (
Expand Down
1 change: 1 addition & 0 deletions Misc/ACKS
Original file line number Diff line number Diff line change
Expand Up @@ -1484,6 +1484,7 @@ Václav Šmilauer
Allen W. Smith
Christopher Smith
Eric V. Smith
Ethan Smith
Gregory P. Smith
Mark Smith
Roy Smith
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
``functools.singledispatch`` now supports decorating and registering with
methods.