mrocklin / multipledispatch

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

Add decorator that automatically infers signature based on type annotations #119

Open ToniBig opened 2 years ago

ToniBig commented 2 years ago

It would be great to have a decorator that would not need an explicit parameter signature , when all of a functions parameters were annotated using typing capabilities. If this possibily already exists please tell me how it's done.

Right now I have to / can use the dispactch decorator like this:

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

@dispatch(object, object)
    def add(x, y):
        return "%s + %s" % (x, y)

In the case of fully annotated functions would it not be possibly to provide a decorator that would work just like that(?):

@dispatch_auto
    def add(x: int, y: int):
        return x + y

@dispatch_auto
    def add(x: object, y: object):
        return "%s + %s" % (x, y)
astanziola commented 2 years ago

Isn't that what functools.singledispatch does? https://docs.python.org/3/library/functools.html

ToniBig commented 2 years ago

Using that seems kind of clunky, since you have to use @fun.register also. As stated above I was thinking of a interface similar to multidispatch without to need to redundantly provide types to the decorator.

cocolato commented 2 years ago

I think it is auto inferred now:

from multipledispatch import dispatch

if __name__ == "__main__":

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

    @dispatch()
    def add(x: object, y: object):
        return "%s + %s" % (x, y)

    print(add(1, 2)) # 3
    print(add("1", "2")) # 1+2
JuanFMontesinos commented 2 years ago

It doesn't work when there are kwargs unless explicity stated:

from multipledispatch import dispatch

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

@dispatch(object,object)
def add(x: object, y: object,jesus=None):
    return "%s + %s" % (x, y)

print(add(1, 2))  # 3
print(add("1", "2"))  # 1+2

Works

from multipledispatch import dispatch

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

@dispatch()
def add(x: object, y: object,jesus=None):
    return "%s + %s" % (x, y)

print(add(1, 2))  # 3
print(add("1", "2"))  # 1+2

Doesn't work