[New-bugs-announce] [issue32380] functools.singledispatch interacts poorly with methods

Ethan Smith report at bugs.python.org
Tue Dec 19 17:23:08 EST 2017

New submission from Ethan Smith <ethan at ethanhs.me>:

Consider the following:

from functools import singledispatch

class Dispatch:
    def foo(self, a):
        return a

    def _(self, a):
        return "int"

    def _(self, a):
        return "str"

cls = Dispatch()
cls.foo(3)  # 3
cls.foo('hm')  # 'hm'

I find this quite unintuitive. Essentially, since singledispatch dispatches based solely on a functions first argument, it is useless on methods unless one wraps it and modifies how it uses the internal wrapper function. I believe this should be relatively easy to fix with adding a check of inspect.ismethod and then modifying the number of the checked argument where appropriate.

I'm happy to write a patch if this change is seen as a good idea.

components: Library (Lib)
messages: 308687
nosy: Ethan Smith
priority: normal
severity: normal
status: open
title: functools.singledispatch interacts poorly with methods
type: behavior
versions: Python 3.6

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list