<div dir="ltr"><div><div><div><div><div><div><div>Hello all,<br><br></div>In <a href="https://bugs.python.org/issue32380">https://bugs.python.org/issue32380</a> I was hoping to add support for singledispatch with methods. Unfortunately, this cannot be achieved internally without ugly attribute or stack hacks. <br></div><div><br></div><div>Therefore, I was thinking it would be nice if singledispatch supported a keyword argument of the argument index to dispatch on, thus one can say:<br><br></div>class A:<br></div>    @singledispatch(arg=1)<br></div>    def method(self, a):<br></div>        return 'base'<br>    @method.register(int)<br>    def method(self, a):<br>        return 'int'<br><br></div>The other option that could work is to define a special decorator for methods<br><br>def methodsingledispatch(func):<br>    """Single-dispatch generic method decorator."""<br>    wrapped = singledispatch(func)<br>    def wrapper(*args, **kw):<br>        return wrapped.dispatch(args[1].__class__)(*args, **kw)<br>    wrapper.register = wrapped.register<br>    update_wrapper(wrapper, func)<br>    return wrapper<br></div><div><br></div><div>Since this is an API change, Ivan said I should post here to get feedback.</div><div><br></div><div>I prefer the first design, as it is more generic and flexible.</div><div><br></div><div>There is also the issue of classmethod and staticmethod. Since these are descriptors, I'm not sure they will work with singledispatch at all.</div><div><br></div><div>if you do<br></div><div><br></div><div>@classmethod<br>@singledispatch<br>def foo(cls, arg): ...</div><div><br></div><div>You lose register on foo, breaking everything. I believe this would require changing classmethod thus is a non-starter.</div><div><br></div><div>If you do<br></div><div><br></div><div>@singledispatch<br>@classmethod<br>def foo(arg): ...<br></div><div><br></div><div>The wrapper in singledispatch needs to be called as the __func__ in classmethod, but __func__ is readonly.</div><div><br></div><div>So at the moment, I don't think it is possible to implement singledispatch on classmethod or staticmethod decorated functions.<br></div><div><br></div><div>I look forward to people's thoughts on these issues.<br></div><div><br></div><div>Cheers,</div><div><br></div><div>Ethan Smith<br></div></div>