pythonmultimethodmultiple-dispatch

Is there any difference between multimethod and multipledispatch?


I would like to use overloading in Python. I know it's not possible by design (Python is dynamically typed language), there is quite good thread here on this topic. That's why I could use something like multiple dispatch (multimethods). And I'm thinking about the best solution, that would implement multiple dispatch for any function or class method. Is there any solution that is natively included in Python?

Using singledispatch (added to Python in 3.4) is not enough in my case (because only the type of the first argument is considered and I need multiple).

I also know that I could use keyword arguments (i.e. having single function and drive the behavior by checking all arguments), but it's getting complicated when you have a lot of arguments and combinations.

So far, I was able to find these two libraries (not included in the Python Standard Library):

The basic usage looks like:

from multimethod import multimethod

@multimethod
def add(x: int, y: int):
    ...

@multimethod
def add(x: str, y: str):
    ...

or

from multipledispatch import dispatch

@dispatch(int, int)
def add(x, y):
    ...

@dispatch(str, str)
def add(x, y):
    ...

This functionality seems very similar.

I have mainly two questions:


Solution

  • My reasons on why multimethod is vastly better compared to multipledispatch

    1. Type information we add into method signature, not in the decorator signature. Doing so, is much intuitive and cleaner.
    2. Type hinting of multimethod is same as expected by static type support/mypy. Now, type annotation becoming common among Developers. So, this helps in both way! Multimethod type hinting is officially same as mypy type hinting
    3. Please note, be it multi method or multiple dispatch, seems they support only non-keyword function call. If you call a function with keywords on the call, both fails. This is disappoint, but they may have more reasons to do so. Please read the guides of respective modules. They talk about keywords based function call, but not very clear, IMO. Hence, Some times I feel, simple type checking in our function would solve all problems at once instead of using multimethod or multiple dispatch. After all, I want, first class solution since function are first class objects.
    4. As I know, there is no solution in the language for Polymorphism/function overloading. But multimethod look Pythonic and native. I just like it. Further, multimethod also support single dispatch, though I never felt need of it.
    5. Thank you for your question. You have already answered. I was unaware of exact difference until I read your question. And you have already provided answer. Thank you for the Question.