python method overloading – multipledispatch with kwargs

I’m using python3.8 and multipledispatch library in order to overload a method signature.

multipledispatch documentation examples suggests overloading like this:

from multipledispatch import dispatch


@dispatch(int, int)
def add(x, y):
    print(x + y)


@dispatch(str, str)
def add(x, y):
    print(f'{x} {y}')


add(1, 2)
add('hello', 'world')

but in my case I want to call add with keyword arguments like this:

add(x=1, y=2)
add(x='hello', y='world')

and I also want to use it with default values like this:

from multipledispatch import dispatch


@dispatch(int, int)
def add(x=2, y=1):
    print(x + y)


@dispatch(str, str)
def add(x='hello', y='world'):
    print(f'{x} {y}')


add(x=1)
add(y='world')

when trying to use it that way, dispatch decorator ignores the kwargs and throws the following exception:

Traceback (most recent call last):
  File "/home/tomer/.virtualenvs/sqa/lib/python3.8/site-packages/multipledispatch/dispatcher.py", line 269, in __call__
    func = self._cache[types]
KeyError: ()

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/tomer/windows-automation-testing/sqa/try.py", line 22, in <module>
    add(x=1, y=2)
  File "/home/tomer/.virtualenvs/sqa/lib/python3.8/site-packages/multipledispatch/dispatcher.py", line 273, in __call__
    raise NotImplementedError(
NotImplementedError: Could not find signature for add: <>

Source: Python Questions

LEAVE A COMMENT