I'm making the transition over to Python3 and have been exploring some of the functionality of the stdlib. functools.singledispatch caught my eye and I've been playing around with it a little bit. However, at the point where I tried using it in a class I ran into some problems.
It doesn't appear to work with functions registered inside the class, you can make it work by directly calling fun.dispatch(type(arg))(argname=arg) and I was wondering if there was a better way to do it.
I tried using @classmethod and @staticmethod as decorators above and below the registration but that didn't work.
Here's a contrived example that registers handlers to convert the input argument when creating a class to ensure that it will always be a list.
from functools import singledispatch
class UrlDispatcher(object):
@singledispatch
def url_input(self, input):
print('input wasn\'t dispatched', input)
@url_input.register(str)
def _(self, input):
print('input is a str', input)
self.input = [input]
@url_input.register(list)
def _(self, input):
print('input is a list', input)
self.input = input
def __init__(self, arg):
# Works, albeit clunkily
self.url_input.dispatch(type(arg))(self,input=arg)
# Always uses the base dispatcher
self.url_input(input=arg)
a = "http://www.cnn.com"
b = ["http://www.google.com", "http://www.slashdot.org"]
s1 = UrlDispatcher(a)
s2 = UrlDispatcher(b)