coady / multimethod

Multiple argument dispatching.
https://coady.github.io/multimethod
Other
277 stars 24 forks source link

Add interface like singledispatchmethod #6

Closed Dr-ZeeD closed 4 years ago

Dr-ZeeD commented 4 years ago

Python 3.8 saw the introduction of functools.singledispatchmethod. I would love to see support for the same interface in a multipledispatchmethod.

coady commented 4 years ago

Methods are already supported:

class Negator: 
    @multimethod 
    def neg(self, arg: int): 
        return -arg 

    @neg.register 
    def _(self, arg: bool): 
        return not arg                                                                                                                                                                                                                                         

In []: Negator().neg(1)                                                                                                                                                                                                                        
Out[]: -1

In []: Negator().neg(True)                                                                                                                                                                                                                     
Out[]: False

If a param on the left has no annotation, it's equivalent to having an : object annotation.

Dr-ZeeD commented 4 years ago

Actually, I was thinking of support of the register method without type annotation. But I reckon it's possible using object as first type?

coady commented 4 years ago

Ah, yes: .register(object, ...) works.

I guess it's time to fully support and document @register(*types). This project pre-dates Python 3 and singledispatch, and it wasn't clear if annotations would be preferred. But the original singledispatch style still seems popular, even with the end of Python 2.

coady commented 4 years ago

da2fdb3 documents this feature more clearly. Thanks.