Skip to content

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

Open

Description

@ToniBig

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)

Activity

  1. astanziola commented on Jan 14, 2022

    @astanziola

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

  2. ToniBig commented on Jan 14, 2022

    @ToniBig
    Author

    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.

  3. cocolato commented on Feb 17, 2022

    @cocolato

    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
    
  4. JuanFMontesinos commented on Apr 1, 2022

    @JuanFMontesinos

    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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions