mrocklin / multipledispatch

Multiple dispatch
https://multiple-dispatch.readthedocs.io/en/latest/
Other
811 stars 72 forks source link

Adding convinient, shorter syntax variant for Dispatcher #86

Open stereobutter opened 6 years ago

stereobutter commented 6 years ago

I often encounter use cases where I want to dispatch just a few different types to very short functions (such that lambdas would suffice). Take for example:

@dispatch(int)
def f(x): return 2*x

@dispatch(str)
def f(x): return 3*x

What is imho. missing is a nice, shorter syntax variant. I propose something like

f = Map(int=lambda x: 2*x, str=lambda x: 3*x)

where Map is

def Map(**kwargs):
    f = Dispatcher('lambda')
    for key, func in kwargs.items():
        f.register(eval(key))(func)
    return f
stereobutter commented 6 years ago

Issues with the proposal above are:

  1. No support for functions with multiple argument, since expressions are not allowed as keyword arguments e.g. Map((int,int)=lambda x,y: x+y, ...). A possible solution to this is using Map({(int,int):lambda x,y: x+y, ...}) which is valid python syntax, albeit not as nice to look at.

  2. No support for union types; same reason as above. Additionally in the above solution using Map({(int,int):lambda x,y: x+y, ...}) there is the issue with supporting both union of types and multiple arguments. Should (int, str) denote a two argument function that expects an int and a str or a unary function that expects either an int or a str?

I still think a feature like this would be useful even with limited (and clearly outlined) application, given that for more complicated cases one would use the traditional syntax anyway

@dispatch(...)
def f(...):
    ....