It's a little difficult to achieve what you're trying to do in Python. singledispatch
and singledispatchmethod
are both themselves relatively new features in the language. More complex overloading such as what you're attempting isn't particularly well supported at the moment (to my knowledge).
Having said that, you could try the below, using the third-party multipledispatch
module. It feels like a little bit of a hack, though, and I'm not sure how to make it work on class methods -- the below solution only works for instance methods.
from multipledispatch import dispatch
@dispatch(object, object)
def handle(instance, arg):
return 'Base implementation'
class A:
def handle(self, arg):
return handle(self, arg)
class B(A):
pass
class C(A):
pass
@dispatch(B, int)
def handle(instance, arg):
return 'Specialised implementation for class B and ints'
@dispatch(C, str)
def handle(instance, arg):
return 'Specialised implementation for class C and strs'
a, b, c = A(), B(), C()
print(a.handle('hi')) # prints "Base implementation"
print(b.handle('hi')) # prints "Base implementation"
print(b.handle(3)) # prints "Specialised implementation for class B and ints"
print(c.handle(3)) # prints "Base implementation"
print(c.handle('hi')) # prints "Specialised implementation for class C and strs"
You might be able to get even closer to your desired result with the plum-dispatch
module, another third-party module on pip. I don't know much about it, but I gather it has some extra features that multipledispatch
doesn't.